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
GDGT-1582: Schema Viewer (Entity Relationship Diagram) (#71351)
Stas Gavrylov0b10c75bdbcc
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex a145b2beddc..eefd5fb81c5 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -3068,6 +3068,16 @@;; make token tracking a hook). Drop this dep once the relocation lands.:uses #{enterprise/semantic-search}}+ enterprise/erd+ {:team "Gadget"+ :api #{metabase-enterprise.erd.api}+ :uses #{api+ models+ util}+ :model-imports #{:model/Database+ :model/Field+ :model/Table}}+enterprise/gsheets{:team "Cloud":api #{metabase-enterprise.gsheets.apidiff --git a/e2e/test/scenarios/schema-viewer/schema-viewer.cy.spec.ts b/e2e/test/scenarios/schema-viewer/schema-viewer.cy.spec.tsnew file mode 100644index 00000000000..adaa34988f0--- /dev/null+++ b/e2e/test/scenarios/schema-viewer/schema-viewer.cy.spec.ts@@ -0,0 +1,589 @@+const { H } = cy;++import {+ MAGIC_USER_GROUPS,+ SAMPLE_DB_ID,+ WRITABLE_DB_ID,+} from "e2e/support/cypress_data";+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import { checkNotNull } from "metabase/utils/types";+import type { TableId } from "metabase-types/api";++const { ORDERS_ID, PEOPLE_ID, PRODUCTS_ID, REVIEWS_ID } = SAMPLE_DATABASE;++const BASE_URL = "/data-studio/schema-viewer";+const PUBLIC_SCHEMA = "PUBLIC";+const ERD_ALIAS = "erd";++// Layout constants mirrored from the SchemaViewer source. Keep in sync.+const MIN_ZOOM = 0.3;+const MIN_ZOOM_FOR_TARGET = 0.5;++const SV_SCHEMA = "sv_test";+const SV_EXTRA_SCHEMA = "sv_extra";++// Postgres setup creating two schemas and a few tables that exercise+// scenarios the Sample Database doesn't naturally cover:+// - sv_test.users / sv_test.profiles → one-to-one (shared PK)+// - sv_test.categories.parent_id → categories.id (self-reference)+// - sv_test.products.lookup_id → sv_extra.lookup.id (cross-schema FK)+// - sv_extra.other — a second cross-schema table with no relationship,+// used to differentiate URL-supplied table-ids from UKV-saved ones in+// the precedence test.+const SV_SETUP_SQL = `+ DROP SCHEMA IF EXISTS sv_test CASCADE;+ DROP SCHEMA IF EXISTS sv_extra CASCADE;+ CREATE SCHEMA sv_extra;+ CREATE SCHEMA sv_test;+ CREATE TABLE sv_extra.lookup (+ id SERIAL PRIMARY KEY,+ code TEXT+ );+ CREATE TABLE sv_extra.other (+ id SERIAL PRIMARY KEY,+ label TEXT+ );+ CREATE TABLE sv_test.users (+ id SERIAL PRIMARY KEY,+ name TEXT NOT NULL+ );+ CREATE TABLE sv_test.profiles (+ user_id INTEGER PRIMARY KEY REFERENCES sv_test.users(id),+ bio TEXT+ );+ CREATE TABLE sv_test.categories (+ id SERIAL PRIMARY KEY,+ name TEXT NOT NULL,+ parent_id INTEGER REFERENCES sv_test.categories(id)+ );+ CREATE TABLE sv_test.products (+ id SERIAL PRIMARY KEY,+ lookup_id INTEGER REFERENCES sv_extra.lookup(id)+ );+`;++const tableNode = (tableId: TableId) => cy.get(`[data-id="table-${tableId}"]`);+const schemaPickerTrigger = () => cy.findByTestId("schema-picker-button");+const searchInput = () => cy.findByTestId("schema-viewer-node-search-input");+const infoPanel = () => cy.findByTestId("graph-info-panel");+const reactFlowViewport = () => cy.get(".react-flow__viewport");++function assertViewportZoom(matcher: (zoom: number) => void) {+ reactFlowViewport().should(($el) => {+ const style = $el.attr("style") ?? "";+ const match = /scale\(([\d.]+)\)/.exec(style);+ expect(match, `viewport transform should contain scale(...): ${style}`).to+ .not.be.null;+ matcher(parseFloat(checkNotNull(match)[1]));+ });+}++function assertNodeInViewport(tableId: TableId) {+ cy.get(".react-flow").should(($reactFlowNode) => {+ const viewportRect = $reactFlowNode[0].getBoundingClientRect();+ const $tableNode = Cypress.$(`[data-id="table-${tableId}"]`);+ expect(+ $tableNode.length,+ `table-${tableId} should be in the DOM`,+ ).to.be.greaterThan(0);+ const tableNodeRect = $tableNode[0].getBoundingClientRect();+ const overlaps =+ tableNodeRect.right > viewportRect.left &&+ tableNodeRect.left < viewportRect.right &&+ tableNodeRect.bottom > viewportRect.top &&+ tableNodeRect.top < viewportRect.bottom;+ expect(+ overlaps,+ `table-${tableId} bounding rect should overlap the React Flow viewport`,+ ).to.be.true;+ });+}++describe("scenarios > schema-viewer (premium gating)", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ cy.intercept("GET", "/api/ee/erd*").as(ERD_ALIAS);+ });++ it("renders the upsell page and never calls the ERD endpoint when :dependencies is not licensed", () => {+ cy.log("Visit the schema viewer URL without activating a token");+ cy.visit(BASE_URL);++ cy.log("Upsell page is shown");+ cy.findByRole("heading", {+ name: "Visualize your database structure",+ }).should("be.visible");++ cy.log("ERD endpoint was never called");+ cy.get(`@${ERD_ALIAS}.all`).should("have.length", 0);+ });+});++describe("scenarios > schema-viewer (Sample Database happy path)", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ cy.intercept("GET", "/api/ee/erd*").as(ERD_ALIAS);+ });++ it("walks the full picker → canvas → selection → info panel → search → layout flow on the Sample Database", () => {+ cy.log("Bare URL renders the empty state with the picker auto-opened");+ cy.visit(BASE_URL);+ cy.findByTestId("schema-picker-button")+ .findByText("Pick a schema to view")+ .should("be.visible");++ cy.log("Pick the Sample Database from the picker");+ H.miniPicker().findByText("Sample Database").click();+ H.miniPicker().findByText("PUBLIC").click();++ cy.log("Single-schema DB auto-navigates into PUBLIC and fetches ERD");+ cy.wait("@erd")+ .its("request.url")+ .should("include", `database-id=${SAMPLE_DB_ID}`)+ .and("include", `schema=${PUBLIC_SCHEMA}`);+ cy.url().should("include", `database-id=${SAMPLE_DB_ID}`);+ cy.url().should("include", `schema=${PUBLIC_SCHEMA}`);++ cy.log("All four FK-connected sample tables render as nodes");+ tableNode(ORDERS_ID).should("be.visible");+ tableNode(PRODUCTS_ID).should("be.visible");+ tableNode(PEOPLE_ID).should("be.visible");+ tableNode(REVIEWS_ID).should("be.visible");++ cy.log("Edges are rendered between FK-related tables");+ cy.get(".react-flow__edge").should("have.length.at.least", 3);++ cy.log("Click the Orders table header to select the node");+ tableNode(ORDERS_ID).findByText("ORDERS").click();++ cy.log("Side info panel opens with the table breadcrumb and field list");+ infoPanel()+ .should("be.visible")+ .and("contain", "ORDERS")+ .and("contain", "Sample Database")+ .and("contain", "PUBLIC")+ .and("contain", "USER_ID")+ .and("contain", "PEOPLE");++ cy.log("Read-only adapter: no 'Find and replace' / 'Replace' button");+ infoPanel()+ .findByRole("button", { name: /Replace/i })+ .should("not.exist");++ cy.log("Click panel title — camera re-zooms to the selected Orders node");+ infoPanel().findByRole("heading", { name: "ORDERS" }).click();+ assertViewportZoom((z) =>+ expect(z, "title click should zoom correctly").to.be.at.least(+ MIN_ZOOM_FOR_TARGET,+ ),+ );+ assertNodeInViewport(ORDERS_ID);++ cy.log(+ "Click an FK link inside the info panel — camera pans to the target",+ );+ infoPanel()+ .findByRole("button", { name: /Products/i })+ .click();+ assertNodeInViewport(PRODUCTS_ID);+ cy.log("Selection stays on Orders after FK link click");+ infoPanel().findByRole("heading", { name: "ORDERS" }).should("be.visible");++ cy.log("Auto-layout fits the entire canvas — every table is on screen");+ cy.contains("button", "Auto-layout").should("be.visible").click();+ assertNodeInViewport(ORDERS_ID);+ assertNodeInViewport(PRODUCTS_ID);+ assertNodeInViewport(PEOPLE_ID);+ assertNodeInViewport(REVIEWS_ID);+ cy.log("Auto-layout zoom is within React Flow's clamp range (>= MIN_ZOOM)");+ assertViewportZoom((z) =>+ expect(z, "auto-layout zoom should be at least MIN_ZOOM").to.be.at.least(+ MIN_ZOOM,+ ),+ );++ cy.log("Re-select Orders, then Focus-node zooms in onto Orders");+ tableNode(ORDERS_ID).findByText("ORDERS").click();+ cy.contains("button", "Focus node").should("be.visible").click();+ assertViewportZoom((z) =>+ expect(z, "focus-node should be zoomed in").to.be.at.least(+ MIN_ZOOM_FOR_TARGET,+ ),+ );+ assertNodeInViewport(ORDERS_ID);++ cy.log(+ "Double-click Reviews — camera zooms in onto Reviews and re-enables the focus-node button",+ );+ tableNode(REVIEWS_ID).findByText("REVIEWS").dblclick();+ assertViewportZoom((z) =>+ expect(z, "double-click should zoom in").to.be.at.least(+ MIN_ZOOM_FOR_TARGET,+ ),+ );+ assertNodeInViewport(REVIEWS_ID);+ cy.contains("button", "Focus node").should("not.be.disabled");++ cy.log("Selection moved from Orders to Reviews — prior selection cleared");+ infoPanel().findByRole("heading", { name: "REVIEWS" }).should("be.visible");+ infoPanel().findByRole("heading", { name: "ORDERS" }).should("not.exist");++ cy.log("Closing the info panel clears node selection");+ infoPanel().findByLabelText("Close").click({ force: true });+ cy.findByTestId("graph-info-panel").should("not.exist");+ cy.contains("button", "Focus node").should("not.exist");++ cy.log(+ "Clicking the USER_ID FK on Orders (target on canvas) selects the connecting edge and pans the camera",+ );++ tableNode(ORDERS_ID).findByText("USER_ID").click({ force: true });+ assertNodeInViewport(PEOPLE_ID);+ cy.findAllByTestId("schema-viewer-edge-path")+ .filter('[data-selected="true"]')+ .should("have.length", 1);++ cy.log(+ "Re-clicking the now-selected edge alternates the camera between source and target endpoints",+ );+ const selectedEdge = () => cy.get(".react-flow__edge.selected");+ selectedEdge().click({ force: true });+ reactFlowViewport().invoke("attr", "style").as("zoomToSourceEnd");+ selectedEdge().click({ force: true });+ cy.get<string>("@zoomToSourceEnd").then((sourceTransform) => {+ reactFlowViewport()+ .invoke("attr", "style")+ .should((style) =>+ expect(+ style,+ "next click on the same edge should zoom to the OTHER endpoint",+ ).to.not.equal(sourceTransform),+ );+ });++ cy.log(+ "Search input filters by name; selecting an option triggers the camera",+ );+ searchInput().click().should("be.focused").type("ord");+ cy.findByRole("option", { name: /Orders/i }).should("be.visible");+ searchInput().type("{enter}");+ assertNodeInViewport(ORDERS_ID);++ cy.log("Empty result shows 'No tables found'");+ searchInput().click().clear().type("zzz_nope_zzz");+ cy.findByTestId("schema-viewer-node-search-dropdown")+ .findByText("No tables found")+ .should("be.visible");+ searchInput().type("{esc}");+ });++ it("URL state survives a hard reload, and the bare URL redirects back to the last opened (DB, schema)", () => {+ cy.log("Deep-link directly to Sample DB → PUBLIC");+ cy.visit(`${BASE_URL}?database-id=${SAMPLE_DB_ID}&schema=${PUBLIC_SCHEMA}`);+ cy.wait("@erd");+ tableNode(ORDERS_ID).should("be.visible");++ cy.log("Hard reload reproduces the same canvas state");+ cy.reload();+ cy.wait("@erd");+ tableNode(ORDERS_ID).should("be.visible");+ tableNode(PRODUCTS_ID).should("be.visible");++ cy.log("Visiting the bare URL redirects to the last opened (DB, schema)");+ cy.visit(BASE_URL);+ cy.wait("@erd");+ cy.url()+ .should("include", `database-id=${SAMPLE_DB_ID}`)+ .and("include", `schema=${PUBLIC_SCHEMA}`);+ tableNode(ORDERS_ID).should("be.visible");+ });++ it("opens the picker with the current selection highlighted, and supports Back navigation between databases and schemas", () => {+ cy.visit(`${BASE_URL}?database-id=${SAMPLE_DB_ID}&schema=${PUBLIC_SCHEMA}`);+ cy.wait("@erd");+ tableNode(ORDERS_ID).should("be.visible");++ cy.log("Picker trigger shows the current schema name");+ schemaPickerTrigger().should("contain", PUBLIC_SCHEMA);++ cy.log(+ "Open the picker — drills directly into the schema list of the current DB",+ );+ schemaPickerTrigger().click();+ H.miniPicker().findByText("Sample Database").should("be.visible");++ cy.log("Click outside the popover closes it");+ cy.get("body").click(0, 0);+ H.miniPicker().should("not.exist");+ });+});++describe("scenarios > schema-viewer (writable Postgres: multi-schema, self-ref, one-to-one, cross-schema FK)", () => {+ beforeEach(() => {+ H.restore("postgres-writable");+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ cy.intercept("GET", "/api/ee/erd*").as(ERD_ALIAS);+ H.queryWritableDB(SV_SETUP_SQL, "postgres");+ H.resyncDatabase({ dbId: WRITABLE_DB_ID });+ });++ after(() => {+ H.queryWritableDB(+ "DROP SCHEMA IF EXISTS sv_test CASCADE; DROP SCHEMA IF EXISTS sv_extra CASCADE;",+ "postgres",+ );+ });++ it("drills into a multi-schema DB via the picker, renders self-ref + one-to-one + cross-schema edges, expands an off-canvas FK target, and persists the expansion", () => {+ cy.log("Capture writable-DB table IDs created by the setup SQL");+ H.getTableId({+ databaseId: WRITABLE_DB_ID,+ name: "users",+ schema: SV_SCHEMA,+ }).as("usersId");+ H.getTableId({+ databaseId: WRITABLE_DB_ID,+ name: "profiles",+ schema: SV_SCHEMA,+ }).as("profilesId");+ H.getTableId({+ databaseId: WRITABLE_DB_ID,+ name: "categories",+ schema: SV_SCHEMA,+ }).as("categoriesId");+ H.getTableId({+ databaseId: WRITABLE_DB_ID,+ name: "products",+ schema: SV_SCHEMA,+ }).as("productsId");+ H.getTableId({+ databaseId: WRITABLE_DB_ID,+ name: "lookup",+ schema: SV_EXTRA_SCHEMA,+ }).as("lookupId");++ cy.log("Bare URL — picker auto-opens with both databases listed");+ cy.visit(BASE_URL);+ H.miniPicker().findByText("Sample Database").should("be.visible");+ H.miniPicker().findByText("Writable Postgres12").should("be.visible");++ cy.log("Multi-schema DB drills into the schema list (no auto-nav)");+ H.miniPicker().findByText("Writable Postgres12").click();+ H.miniPicker().findByText(SV_SCHEMA).should("be.visible");+ H.miniPicker().findByText(SV_EXTRA_SCHEMA).should("be.visible");++ cy.log(`Click ${SV_SCHEMA} → navigates and ERD loads`);+ H.miniPicker().findByText(SV_SCHEMA).click();+ cy.wait("@erd");+ cy.url()+ .should("include", `database-id=${WRITABLE_DB_ID}`)+ .and("include", `schema=${SV_SCHEMA}`);++ cy.log("All four sv_test tables render as nodes");+ cy.get<TableId>("@usersId").then((id) =>+ tableNode(id).should("be.visible"),+ );+ cy.get<TableId>("@profilesId").then((id) =>+ tableNode(id).should("be.visible"),+ );+ cy.get<TableId>("@categoriesId").then((id) =>+ tableNode(id).should("be.visible"),+ );+ cy.get<TableId>("@productsId").then((id) =>+ tableNode(id).should("be.visible"),+ );++ cy.log(+ "Schema-bounded BFS: cross-schema lookup is NOT a node yet — it surfaces only as an FK pointer on products",+ );+ cy.get<TableId>("@lookupId").then((id) =>+ tableNode(id).should("not.exist"),+ );++ cy.log(+ "Edges visible: users<->profiles (one-to-one) and categories self-ref. Cross-schema FK has no edge until expansion",+ );+ cy.get(".react-flow__edge").should("have.length", 2);++ cy.log(+ "Clicking the profiles.user_id FK (target on canvas) selects the connecting edge",+ );+ cy.get<TableId>("@profilesId").then((id) =>+ tableNode(id).findByText("user_id").click(),+ );+ cy.findAllByTestId("schema-viewer-edge-path")+ .filter('[style*="stroke-width: 2"]')+ .should("have.length", 1);++ cy.log(+ "Click the cross-schema FK on products.lookup_id — adds sv_extra.lookup to the canvas",+ );+ cy.get<TableId>("@productsId").then((id) =>+ tableNode(id).findByText("lookup_id").click({ force: true }),+ );+ cy.wait("@erd");+ cy.get<TableId>("@lookupId").then((id) => {+ tableNode(id).should("be.visible");+ assertNodeInViewport(id);+ });+ cy.log("Edge count grows by one (products → lookup edge added)");+ cy.get(".react-flow__edge").should("have.length", 3);++ cy.log(+ "Reload — the expanded lookup table persists via UKV (URL stays untouched, canvas keeps the table)",+ );+ cy.reload();+ cy.wait("@erd");+ cy.get<TableId>("@lookupId").then((id) => {+ tableNode(id).should("be.visible");+ });+ cy.get(".react-flow__edge").should("have.length", 3);++ cy.log(+ "URL precedence: visit the same context with table-ids=<other> — URL must win, the UKV-saved lookup is ignored",+ );+ H.getTableId({+ databaseId: WRITABLE_DB_ID,+ name: "other",+ schema: SV_EXTRA_SCHEMA,+ }).as("otherId");+ cy.get<TableId>("@otherId").then((otherId) => {+ cy.visit(+ `${BASE_URL}?database-id=${WRITABLE_DB_ID}&schema=${SV_SCHEMA}&table-ids=${otherId}`,+ );+ });+ cy.wait("@erd").then(({ request }) => {+ cy.get<TableId>("@otherId").then((otherId) => {+ expect(+ request.url,+ "ERD request should carry the URL-supplied table-ids",+ ).to.include(`table-ids=${otherId}`);+ });+ cy.get<TableId>("@lookupId").then((lookupId) => {+ expect(+ request.url,+ "ERD request must NOT include the UKV-saved table-ids",+ ).to.not.include(`table-ids=${lookupId}`);+ });+ });+ cy.log("Canvas reflects URL precedence: `other` is shown, `lookup` is not");+ cy.get<TableId>("@otherId").then((id) =>+ tableNode(id).should("be.visible"),+ );+ cy.get<TableId>("@lookupId").then((id) =>+ tableNode(id).should("not.exist"),+ );+ });+});++describe("scenarios > schema-viewer (entry points + loader/error states)", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ });++ it("Data Studio sidebar tab and Data Model 'Schema viewer' button both lead into the schema viewer", () => {+ cy.intercept("GET", "/api/ee/erd*").as(ERD_ALIAS);++ cy.log(+ "Click 'Schema viewer' tab in the Data Studio sidebar — opens the bare schema viewer URL",+ );+ cy.visit("/data-studio");+ H.DataStudio.nav().findByText("Schema viewer").click();+ cy.url().should("include", "/data-studio/schema-viewer");+ cy.findByTestId("schema-picker-button")+ .findByText("Pick a schema to view")+ .should("be.visible");++ cy.log("Navigate to the Orders Data Model page via the table picker tree");+ H.DataStudio.nav().findByText("Tables").click();+ cy.findAllByTestId("tree-item").contains("Orders").click();++ cy.log(+ "Click the 'Schema viewer' button in the Orders table section — opens with Orders as focal",+ );+ cy.findByTestId("table-section").findByLabelText("Schema viewer").click();+ cy.wait("@erd");+ cy.url()+ .should("include", "/data-studio/schema-viewer")+ .and("include", `database-id=${SAMPLE_DB_ID}`)+ .and("include", `table-ids=${ORDERS_ID}`);+ tableNode(ORDERS_ID).should("be.visible");+ cy.log("Focal table is on screen");+ assertNodeInViewport(ORDERS_ID);+ });++ it("renders the loader during a slow ERD fetch and the error panel when the request fails", () => {+ cy.log("Force a 500 — error panel renders with the surfaced message");+ cy.intercept("GET", "/api/ee/erd*", { statusCode: 500, body: "boom" }).as(+ "erdError",+ );+ cy.visit(`${BASE_URL}?database-id=${SAMPLE_DB_ID}&schema=${PUBLIC_SCHEMA}`);+ cy.wait("@erdError");+ cy.findByTestId("schema-viewer-error")+ .should("be.visible")+ .should("contain", "boom");+ cy.log(+ "Slow the ERD response — the centred loader appears, then the canvas renders",+ );+ cy.intercept("GET", "/api/ee/erd*", (req) => {+ req.on("response", (res) => {+ res.setDelay(1500);+ });+ req.continue();+ }).as("slowErd");+ H.DataStudio.nav().findByLabelText("Library").click();+ H.DataStudio.nav().findByLabelText("Schema viewer").click();+ H.miniPicker().findByText("Sample Database").click();+ H.miniPicker().findByText("PUBLIC").click();+ cy.findByTestId("schema-viewer-loader").should("be.visible");+ cy.wait("@slowErd");+ cy.findByTestId("schema-viewer-loader").should("not.exist");+ tableNode(ORDERS_ID).should("be.visible");+ });+});++describe("scenarios > schema-viewer (permissions)", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ });++ it("a non-admin Data Studio analyst can open the schema viewer end-to-end", () => {+ cy.log(+ "Promote the normal user to the Data Analysts group so they pass canAccessDataStudio",+ );+ cy.request("GET", "/api/user").then(({ body }) => {+ const normal = body.data.find(+ (u: { email: string }) => u.email === "[email protected]",+ );+ cy.request("POST", "/api/permissions/membership", {+ group_id: MAGIC_USER_GROUPS.DATA_ANALYSTS_GROUP,+ user_id: normal.id,+ });+ });++ cy.signInAsNormalUser();+ cy.intercept("GET", "/api/ee/erd*").as(ERD_ALIAS);+ cy.visit(`${BASE_URL}?database-id=${SAMPLE_DB_ID}&schema=${PUBLIC_SCHEMA}`);+ cy.wait("@erd");++ cy.log(+ "Schema viewer renders for the analyst — Sample DB tables on canvas",+ );+ tableNode(ORDERS_ID).should("be.visible");+ tableNode(PRODUCTS_ID).should("be.visible");+ tableNode(PEOPLE_ID).should("be.visible");+ tableNode(REVIEWS_ID).should("be.visible");++ cy.log("Selection still works for the non-admin user");+ tableNode(ORDERS_ID).findByText("ORDERS").click();+ infoPanel().should("be.visible").and("contain", "ORDERS");+ });+});diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.cljindex a7ae892aa61..9b068d27335 100644--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj@@ -24,6 +24,7 @@[metabase-enterprise.dependencies.api][metabase-enterprise.email.api][metabase-enterprise.embedding-hub.api]+ [metabase-enterprise.erd.api][metabase-enterprise.gsheets.api :as gsheets.api][metabase-enterprise.library.api][metabase-enterprise.metabot-analytics.api]@@ -60,6 +61,7 @@:custom-viz (deferred-tru "Custom Visualizations"):library (deferred-tru "Library"):dependencies (deferred-tru "Dependency Tracking")+ :schema-viewer (deferred-tru "Schema Viewer"):embedding (deferred-tru "Embedding"):remote-sync (deferred-tru "Remote Sync"):etl-connections (deferred-tru "ETL Connections")@@ -119,6 +121,7 @@"/database-routing" (premium-handler metabase-enterprise.database-routing.api/routes :database-routing)"/dependencies" (premium-handler metabase-enterprise.dependencies.api/routes :dependencies)"/email" (premium-handler metabase-enterprise.email.api/routes :cloud-custom-smtp)+ "/erd" (premium-handler metabase-enterprise.erd.api/routes :schema-viewer)"/remote-sync" (premium-handler metabase-enterprise.remote-sync.api/routes :remote-sync)"/replacement" (premium-handler metabase-enterprise.replacement.api/routes :dependencies)"/embedding-hub" (premium-handler metabase-enterprise.embedding-hub.api/routes :embedding)diff --git a/enterprise/backend/src/metabase_enterprise/erd/api.clj b/enterprise/backend/src/metabase_enterprise/erd/api.cljnew file mode 100644index 00000000000..d923f3b07d6--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/erd/api.clj@@ -0,0 +1,21 @@+(ns metabase-enterprise.erd.api+ (:require+ [metabase-enterprise.erd.impl :as impl]+ [metabase.api.macros :as api.macros]+ [metabase.api.routes.common :refer [+auth]]+ [metabase.api.util.handlers :as handlers]))++(api.macros/defendpoint :get "/" :- ::impl/erd-response+ "Return an Entity Relationship Diagram (ERD) for tables and their FK relationships.+ When `table-ids` is provided, those tables are the focal points (and must belong to `database-id`)."+ [_route-params+ {:keys [database-id table-ids schema] :as query-params} :- ::impl/erd-request]+ (impl/erd {:database-id database-id+ :table-ids table-ids+ :schema schema+ :schema-selected? (contains? query-params :schema)}))++(def ^{:arglists '([request respond raise])} routes+ "`/api/ee/erd` routes."+ (handlers/routes+ (api.macros/ns-handler *ns* +auth)))diff --git a/enterprise/backend/src/metabase_enterprise/erd/impl.clj b/enterprise/backend/src/metabase_enterprise/erd/impl.cljnew file mode 100644index 00000000000..dbde20d6c99--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/erd/impl.clj@@ -0,0 +1,326 @@+(ns metabase-enterprise.erd.impl+ "Entity Relationship Diagram (ERD) logic: resolving focal tables,+ one-layer FK expansion, and response building."+ (:require+ [clojure.set :as set]+ [metabase.api.common :as api]+ [metabase.models.interface :as mi]+ [metabase.util :as u]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.malli.registry :as mr]+ [metabase.util.malli.schema :as ms]+ [toucan2.core :as t2]))++;;; -------------------------------------------------- Schema --------------------------------------------------++(mr/def ::erd-field+ [:map+ [:id :int]+ [:name :string]+ [:display_name :string]+ [:database_type :string]+ ;; `base_type` / `effective_type` are emitted so the frontend can use the+ ;; shared `getColumnIcon` helper (which keys off Lib type predicates) instead+ ;; of redoing icon mapping from `database_type` strings.+ [:base_type {:optional true} [:maybe :string]]+ [:effective_type {:optional true} [:maybe :string]]+ [:semantic_type {:optional true} [:maybe :string]]+ [:fk_target_field_id {:optional true} [:maybe :int]]+ [:fk_target_table_id {:optional true} [:maybe :int]]])++;; Mirrors the `:owner` hydration on Table: when `owner_user_id` is set we+;; return the full user shape, otherwise (`owner_email` only) we return a+;; map carrying just `:email`. `nil` covers both no-owner and the+;; `owner_user_id`-points-to-missing-user case.+(mr/def ::erd-owner+ [:maybe+ [:map+ [:id {:optional true} :int]+ [:email :string]+ [:first_name {:optional true} [:maybe :string]]+ [:last_name {:optional true} [:maybe :string]]]])++(mr/def ::erd-node+ [:map+ [:table_id :int]+ [:name :string]+ [:display_name :string]+ [:description {:optional true} [:maybe :string]]+ [:owner {:optional true} ::erd-owner]+ [:schema {:optional true} [:maybe :string]]+ [:db_id :int]+ [:fields [:sequential ::erd-field]]])++(mr/def ::erd-edge+ [:map+ [:source_table_id :int]+ [:source_field_id :int]+ [:target_table_id :int]+ [:target_field_id :int]+ [:relationship [:enum "one-to-one" "many-to-one"]]])++(mr/def ::erd-response+ [:map+ [:nodes [:sequential ::erd-node]]+ [:edges [:sequential ::erd-edge]]])++(mr/def ::erd-request+ [:map+ [:database-id ms/PositiveInt]+ [:table-ids {:optional true} [:maybe (ms/QueryVectorOf ms/PositiveInt)]]+ [:schema {:optional true} [:maybe :string]]])++;;; ---------------------------------------- Phase 1: Resolve focal tables ----------------------------------------++(def ^:private table-select-columns+ "Columns we read from Table: the perm columns needed for `mi/can-read?`+ (`:db_id`, `:is_published`, `:collection_id`) plus the display columns the+ ERD response surfaces (`:description`, owner fields hydrated below)."+ [:id :db_id :name :display_name :schema :is_published :collection_id+ :description :owner_user_id :owner_email])++(defn- schema-clause+ "The rest of the database API treats a blank schema name as the union of nil+ and empty-string schemas. Keep that convention here too."+ [schema]+ (if (= schema "")+ [:or+ [:= :schema nil]+ [:= :schema ""]]+ [:= :schema schema]))++(defn- index-by-id [xs]+ (into {} (map (juxt :id identity)) xs))++(defn- readable-tables+ "Fetch readable, active, visible tables in `database-id`.+ Optional `table-ids` restricts by IDs; optional `schema` restricts by schema.+ `schema=\"\"` matches both nil and empty-string schemas."+ [database-id & {:keys [table-ids schema] :as opts}]+ (if (and (contains? opts :table-ids) (empty? table-ids))+ []+ (let [where (cond-> [:and+ [:= :db_id database-id]+ [:= :active true]+ [:= :visibility_type nil]]+ (contains? opts :table-ids) (conj [:in :id table-ids])+ (contains? opts :schema) (conj (schema-clause schema)))]+ (->> (t2/select :model/Table+ {:select table-select-columns+ :where where})+ (filter mi/can-read?)))))++(defn- readable-table-ids+ [database-id & opts]+ (into #{} (map :id) (apply readable-tables database-id opts)))++;;; ---------------------------------------- Phase 2: Fetch ERD graph ----------------------------------------++(defn- fetch-fields-for-tables+ "Fetch all active fields for the given table IDs.+ Returns a vector of field maps."+ [table-ids]+ (when (seq table-ids)+ (t2/select :model/Field+ {:where [:and+ [:in :table_id table-ids]+ [:= :active true]]})))++(defn- fetch-fields-by-ids+ "Fetch active fields by ID."+ [field-ids]+ (when (seq field-ids)+ (t2/select :model/Field+ {:where [:and+ [:in :id field-ids]+ [:= :active true]]})))++(defn- discover-fk-targets+ "Given a collection of fields, find FK target field IDs that point to tables+ we haven't loaded yet. Returns the set of new table IDs to fetch.+ Checks `loaded-field-by-id` first and only queries the DB for unknown target fields."+ [fields known-table-ids loaded-field-by-id]+ (let [target-field-ids (->> fields (keep :fk_target_field_id) set)]+ (if (empty? target-field-ids)+ #{}+ (let [unknown-fids (remove loaded-field-by-id target-field-ids)+ ;; Resolve known targets from the accumulated map+ table-ids (into #{} (keep (comp :table_id loaded-field-by-id)) target-field-ids)+ ;; Query DB only for truly unknown target fields+ table-ids (if (seq unknown-fids)+ (into table-ids+ (map :table_id)+ (fetch-fields-by-ids unknown-fids))+ table-ids)]+ (set/difference table-ids known-table-ids)))))++(defn- fetch-erd-subgraph+ "Load the focal tables plus one layer of readable FK target tables.++ The focal set is loaded without applying the schema boundary so explicitly+ expanded cross-schema tables can become nodes. The one FK-neighbor layer is+ schema-scoped when a schema was selected; off-schema targets still surface+ later as FK target IDs, but not as nodes."+ [database-id focal-tables schema-selected? schema]+ (let [focal-table-ids (into #{} (map :id) focal-tables)+ focal-fields (fetch-fields-for-tables focal-table-ids)+ focal-field-by-id (index-by-id focal-fields)+ neighbor-table-ids (discover-fk-targets focal-fields focal-table-ids focal-field-by-id)+ neighbor-tables (if schema-selected?+ (readable-tables database-id :table-ids neighbor-table-ids :schema schema)+ (readable-tables database-id :table-ids neighbor-table-ids))+ neighbor-table-ids (into #{} (map :id) neighbor-tables)+ neighbor-fields (fetch-fields-for-tables neighbor-table-ids)+ ;; Batch-hydrate `:owner` once across the whole node set so the+ ;; per-node build doesn't trigger N+1 user lookups.+ all-tables (t2/hydrate (concat focal-tables neighbor-tables) :owner)+ all-fields (concat focal-fields neighbor-fields)]+ {:tables-by-id (index-by-id all-tables)+ :fields-by-table (group-by :table_id all-fields)+ :loaded-field-by-id (index-by-id all-fields)}))++;;; ---------------------------------------- Phase 3: Build response ----------------------------------------++(defn- resolve-external-fk-targets+ "For FK target field IDs referenced by the loaded fields but not present in+ `loaded-field-by-id` (because they live outside the loaded node set),+ resolve each target field's `:table_id` from the DB and filter by the user's+ read permission on that table. Returns `{field-id table-id}` — enough for+ `build-erd-field` to populate `fk_target_table_id` without leaking+ references to tables the user can't read.++ Preserves the original security posture (unreadable targets still get nulled+ downstream) while allowing the frontend to expand readable off-canvas tables."+ [database-id all-fields loaded-field-by-id]+ (let [target-ids (into #{}+ (comp (keep :fk_target_field_id)+ (remove loaded-field-by-id))+ all-fields)]+ (if (empty? target-ids)+ {}+ (let [fields (fetch-fields-by-ids target-ids)+ table-ids (into #{} (map :table_id) fields)+ readable-target-table-ids (readable-table-ids database-id :table-ids table-ids)]+ (into {}+ (comp (filter #(contains? readable-target-table-ids (:table_id %)))+ (map (juxt :id :table_id)))+ fields)))))++(defn- build-erd-field+ "Convert a field to the ERD field shape.+ Nils out FK target references only when the target table is unreadable+ (either missing or the user lacks permission); readable targets outside the+ loaded node set still carry `fk_target_field_id`/`fk_target_table_id` so+ the frontend can offer to expand them."+ [field target-field-id->table-id]+ (let [target-table-id (get target-field-id->table-id (:fk_target_field_id field))]+ {:id (:id field)+ :name (:name field)+ :display_name (:display_name field)+ :database_type (:database_type field)+ :base_type (some-> (:base_type field) u/qualified-name)+ :effective_type (some-> (:effective_type field) u/qualified-name)+ :semantic_type (some-> (:semantic_type field) u/qualified-name)+ :fk_target_field_id (when target-table-id (:fk_target_field_id field))+ :fk_target_table_id target-table-id}))++(defn- build-erd-node+ "Build an ERD node for a table with its fields."+ [table fields target-field-id->table-id]+ {:table_id (:id table)+ :name (:name table)+ :display_name (:display_name table)+ :description (:description table)+ :owner (:owner table)+ :schema (:schema table)+ :db_id (:db_id table)+ :fields (mapv #(build-erd-field % target-field-id->table-id) fields)})++(defn- build-erd-edges+ "Build ERD edges from fields, filtered to only include edges between visible tables."+ [fields-by-table loaded-field-by-id visible-table-ids]+ (let [all-fields (mapcat val fields-by-table)]+ (->> all-fields+ (keep (fn [field]+ (when-let [target-field-id (:fk_target_field_id field)]+ (when-let [target-field (loaded-field-by-id target-field-id)]+ (let [target-table (:table_id target-field)]+ (when (and (contains? visible-table-ids (:table_id field))+ (contains? visible-table-ids target-table))+ {:source_table_id (:table_id field)+ :source_field_id (:id field)+ :target_table_id target-table+ :target_field_id target-field-id+ :relationship (if (and (:database_is_pk field)+ (:database_is_pk target-field))+ "one-to-one"+ "many-to-one")}))))))+ vec)))++(defn- build-erd-response+ "Build the ERD response from fetched subgraph data."+ [database-id {:keys [tables-by-id fields-by-table loaded-field-by-id]}]+ (let [visible-table-ids (set (keys tables-by-id))+ all-fields (mapcat val fields-by-table)+ loaded-target-table-ids (into {} (map (juxt :id :table_id)) (vals loaded-field-by-id))+ external-target-table-ids (resolve-external-fk-targets database-id all-fields loaded-field-by-id)+ target-field-id->table-id (merge external-target-table-ids loaded-target-table-ids)+ nodes (->> visible-table-ids+ (keep (fn [tid]+ (when-let [table (tables-by-id tid)]+ (build-erd-node table+ (get fields-by-table tid [])+ target-field-id->table-id))))+ vec)+ edges (build-erd-edges fields-by-table loaded-field-by-id visible-table-ids)]+ {:nodes nodes+ :edges edges}))++;;; ---------------------------------------- Main entry point ----------------------------------------++(defn- resolve-focal-tables+ [{:keys [database-id table-ids schema-selected? schema]}]+ (let [explicit-table-ids (not-empty (set table-ids))]+ (cond+ schema-selected?+ (let [schema-tables (readable-tables database-id :schema schema)+ explicit-tables (when explicit-table-ids+ (readable-tables database-id :table-ids explicit-table-ids))+ tables (vals (index-by-id (concat schema-tables explicit-tables)))]+ (when (and (empty? schema-tables) (empty? explicit-table-ids))+ (throw (ex-info (tru "No tables found in the specified database/schema")+ {:status-code 404+ :database-id database-id+ :schema schema})))+ tables)++ explicit-table-ids+ (readable-tables database-id :table-ids explicit-table-ids)++ :else+ (let [tables (readable-tables database-id)]+ (when (empty? tables)+ (throw (ex-info (tru "No tables found in the specified database")+ {:status-code 404+ :database-id database-id})))+ tables))))++(defn erd+ "Return an ERD for the given database, optionally scoped by schema and/or+ specific tables.++ Focal-set rules:+ - `schema` set: focal = all readable tables in that schema, plus any+ `table-ids` (which are treated as additional focal tables, typically from+ other schemas the user has expanded into via FK click).+ - no `schema`, `table-ids` set: those are the focal tables.+ - no `schema` or `table-ids`: all readable tables in the database.++ When `schema` is set, the one-layer FK expansion stops at that schema —+ cross-schema FK targets are surfaced on fields (so the UI can offer to expand+ them) but are not loaded as nodes unless explicitly listed in `table-ids`."+ [{:keys [database-id schema-selected?] :as request}]+ (api/read-check :model/Database database-id)+ (let [focal-tables (resolve-focal-tables request)+ subgraph (fetch-erd-subgraph database-id focal-tables schema-selected? (:schema request))]+ (build-erd-response database-id subgraph)))diff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.cljindex f31ce4a72ee..14ecd4d0eec 100644--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj@@ -121,6 +121,7 @@:etl_connections false:etl_connections_pg false:dependencies false+ :schema-viewer false:workspaces false:writable_connection true}(mt/with-temporary-setting-values [custom-viz-enabled true]diff --git a/enterprise/backend/test/metabase_enterprise/erd/erd_test.clj b/enterprise/backend/test/metabase_enterprise/erd/erd_test.cljnew file mode 100644index 00000000000..044f59b62ee--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/erd/erd_test.clj@@ -0,0 +1,456 @@+(ns metabase-enterprise.erd.erd-test+ (:require+ [clojure.test :refer :all]+ [metabase.collections.models.collection :as collection]+ [metabase.permissions.core :as perms]+ [metabase.permissions.models.data-permissions :as data-perms]+ [metabase.test :as mt]+ [metabase.util :as u]))++;;; ---------------------------------------- Test helpers ----------------------------------------++(defn- graph-shape+ "Distill an ERD response into a readable topology map.+ Returns e.g. {:orders [:people :products]+ :people []}+ Table names are lowercased keywords, FK targets are sorted."+ [response]+ (let [id->name (into {} (map (fn [n] [(:table_id n)+ (keyword (u/lower-case-en (:name n)))]))+ (:nodes response))+ edges-by-src (group-by :source_table_id (:edges response))]+ (into (sorted-map)+ (map (fn [node]+ [(keyword (u/lower-case-en (:name node)))+ (vec (sort (keep #(id->name (:target_table_id %))+ (edges-by-src (:table_id node)))))]))+ (:nodes response))))++(defn- erd-request!+ "Make an ERD endpoint request. `opts` is a map with optional keys+ :table-ids (coll), :schema."+ [opts]+ (apply mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id (mt/id)+ (mapcat (fn [[k v]]+ (if (= k :table-ids)+ (mapcat (fn [tid] [:table-ids tid]) v)+ [k v]))+ opts)))++(defn- grant-table-read!+ "Grant view-data + create-queries on a table for a permission group."+ [group-id table-id]+ (data-perms/set-table-permission! group-id table-id :perms/view-data :unrestricted)+ (data-perms/set-table-permission! group-id table-id :perms/create-queries :query-builder))++;;; ---------------------------------------- Graph tests (e2e) ----------------------------------------++;; Sample dataset FK graph:+;; orders → products (via product_id)+;; orders → people (via user_id)+;; reviews → products (via product_id)++(deftest erd-graph-single-focal-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "single focal table expands to FK neighbors"+ (is (= {:orders [:people :products]+ :people []+ :products []}+ (graph-shape (erd-request! {:table-ids [(mt/id :orders)]})))))+ (testing "table with no outbound FKs stays isolated"+ (is (= {:products []}+ (graph-shape (erd-request! {:table-ids [(mt/id :products)]})))))))++(deftest erd-graph-multi-focal-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "two focals sharing an FK target — target discovered once, both have edges"+ (is (= {:orders [:people :products]+ :people []+ :products []+ :reviews [:products]}+ (graph-shape (erd-request! {:table-ids [(mt/id :orders) (mt/id :reviews)]})))))+ (testing "selecting an FK target as focal too doesn't duplicate it"+ (is (= {:orders [:people :products]+ :people []+ :products []+ :reviews [:products]}+ (graph-shape (erd-request! {:table-ids [(mt/id :orders) (mt/id :products) (mt/id :reviews)]})))))))++(deftest erd-graph-field-shape-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "FK fields on nodes carry resolved target IDs, PK fields have nil FK refs"+ (let [response (erd-request! {:table-ids [(mt/id :orders)]})+ orders (first (filter #(= (mt/id :orders) (:table_id %)) (:nodes response)))+ fk-field (first (filter #(= "PRODUCT_ID" (:name %)) (:fields orders)))+ pk-field (first (filter #(= "ID" (:name %)) (:fields orders)))]+ (is (= (mt/id :products :id) (:fk_target_field_id fk-field)))+ (is (= (mt/id :products) (:fk_target_table_id fk-field)))+ (is (= "type/FK" (:semantic_type fk-field)))+ (is (nil? (:fk_target_field_id pk-field)))+ (is (nil? (:fk_target_table_id pk-field)))))))++(deftest erd-external-fk-target-resolution-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "FK field pointing to a readable table beyond the hop budget still carries the target IDs"+ ;; Chain A → B → C. Focal = A, one-layer expansion loads A + B. C is+ ;; outside the loaded node set but readable — B's FK field must still surface+ ;; C's table/field IDs so the frontend can offer to expand to it.+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {c-id :id} {:db_id db-id :name "c" :schema "PUBLIC"}+ :model/Field {c-pk-id :id} {:table_id c-id :name "id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK}+ :model/Table {b-id :id} {:db_id db-id :name "b" :schema "PUBLIC"}+ :model/Field {b-pk-id :id} {:table_id b-id :name "id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK}+ :model/Field {b-c-id :id} {:table_id b-id :name "c_id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/FK+ :fk_target_field_id c-pk-id}+ :model/Table {a-id :id} {:db_id db-id :name "a" :schema "PUBLIC"}+ :model/Field _ {:table_id a-id :name "id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK}+ :model/Field _ {:table_id a-id :name "b_id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/FK+ :fk_target_field_id b-pk-id}]+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-id+ :table-ids a-id)+ nodes-by-name (into {} (map (juxt :name identity)) (:nodes response))+ b-node (get nodes-by-name "b")+ c-id-field (first (filter #(= b-c-id (:id %)) (:fields b-node)))]+ (is (contains? nodes-by-name "a"))+ (is (contains? nodes-by-name "b"))+ (is (not (contains? nodes-by-name "c"))+ "c lives beyond the default hop budget and should not be a node")+ (is (= c-id (:fk_target_table_id c-id-field))+ "c_id FK field should carry the external table ID")+ (is (= c-pk-id (:fk_target_field_id c-id-field))+ "c_id FK field should carry the external target field ID"))))))++(deftest erd-schema-boundary-stops-bfs-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "one-layer FK expansion does not cross the schema boundary; cross-schema FK targets surface as IDs only"+ ;; public.a has FK to erd.b. When the user views schema=public, b must+ ;; not be loaded as a node, but a.b_id must still carry b's table/field IDs+ ;; so the frontend can expand on click.+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {b-id :id} {:db_id db-id :name "b" :schema "erd"}+ :model/Field {b-pk-id :id} {:table_id b-id :name "id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK}+ :model/Table {a-id :id} {:db_id db-id :name "a" :schema "public"}+ :model/Field _ {:table_id a-id :name "id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK}+ :model/Field {a-b-id :id} {:table_id a-id :name "b_id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/FK+ :fk_target_field_id b-pk-id}]+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-id+ :table-ids a-id+ :schema "public")+ nodes-by-name (into {} (map (juxt :name identity)) (:nodes response))+ a-node (get nodes-by-name "a")+ b-id-field (first (filter #(= a-b-id (:id %)) (:fields a-node)))]+ (is (contains? nodes-by-name "a"))+ (is (not (contains? nodes-by-name "b"))+ "cross-schema FK target should not be loaded as a node")+ (is (empty? (:edges response))+ "no edge emitted to a non-node")+ (is (= b-id (:fk_target_table_id b-id-field))+ "b_id FK field should carry the cross-schema table ID")+ (is (= b-pk-id (:fk_target_field_id b-id-field))+ "b_id FK field should carry the cross-schema target field ID"))))+ (testing "explicit cross-schema focal tables are loaded regardless of schema filter"+ ;; User clicks to expand to erd.b → frontend sends table-ids=[a, b]+ ;; while still in schema=public view. b must still be loaded as a node.+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {b-id :id} {:db_id db-id :name "b" :schema "erd"}+ :model/Field {b-pk-id :id} {:table_id b-id :name "id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK}+ :model/Table {a-id :id} {:db_id db-id :name "a" :schema "public"}+ :model/Field _ {:table_id a-id :name "id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK}+ :model/Field _ {:table_id a-id :name "b_id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/FK+ :fk_target_field_id b-pk-id}]+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-id+ :table-ids a-id+ :table-ids b-id+ :schema "public")+ nodes-by-name (into {} (map (juxt :name identity)) (:nodes response))]+ (is (contains? nodes-by-name "a"))+ (is (contains? nodes-by-name "b")+ "explicitly-focal cross-schema table should be loaded as a node"))))))++(deftest erd-graph-self-referential-fk-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "self-referential FK produces edge from table to itself"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {tid :id} {:db_id db-id :name "categories" :schema "PUBLIC"}+ :model/Field {pk-id :id} {:table_id tid :name "id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK}+ :model/Field _ {:table_id tid :name "parent_id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/FK+ :fk_target_field_id pk-id}]+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-id+ :table-ids tid)]+ (is (= {:categories [:categories]}+ (graph-shape response))))))))++;;; ---------------------------------------- Integration tests ----------------------------------------++(deftest erd-endpoint-schema-filter-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "schema param loads every readable table in that schema as focal"+ (let [response (erd-request! {:schema "PUBLIC"})+ node-names (set (map :name (:nodes response)))+ ;; Sample dataset's PUBLIC schema contains these tables. The schema+ ;; param must load every readable table in that schema as focal —+ ;; not a subset.+ expected #{"CATEGORIES" "CHECKINS" "ORDERS" "PEOPLE"+ "PRODUCTS" "REVIEWS" "USERS" "VENUES"}]+ (doseq [node (:nodes response)]+ (is (= "PUBLIC" (:schema node))))+ (is (= expected node-names)+ "every readable table in the schema is present as a node")))+ (testing "schema plus extra table-ids: all schema tables PLUS the external tables"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table _ {:db_id db-id :name "p1" :schema "public"}+ :model/Table _ {:db_id db-id :name "p2" :schema "public"}+ :model/Table {x :id} {:db_id db-id :name "x" :schema "other"}]+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-id+ :schema "public"+ :table-ids x)+ node-names (set (map :name (:nodes response)))]+ (is (= #{"p1" "p2" "x"} node-names)))))))++(deftest erd-endpoint-database-only-and-blank-schema-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "database-only request loads every readable table in the database"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table _ {:db_id db-id :name "nil_schema" :schema nil}+ :model/Table _ {:db_id db-id :name "empty_schema" :schema ""}+ :model/Table _ {:db_id db-id :name "other_schema" :schema "other"}]+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-id)+ node-names (set (map :name (:nodes response)))]+ (is (= #{"nil_schema" "empty_schema" "other_schema"} node-names)))))+ (testing "blank schema request matches nil and empty-string schemas only"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table _ {:db_id db-id :name "nil_schema" :schema nil}+ :model/Table _ {:db_id db-id :name "empty_schema" :schema ""}+ :model/Table _ {:db_id db-id :name "other_schema" :schema "other"}]+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-id+ :schema "")+ node-names (set (map :name (:nodes response)))]+ (is (= #{"nil_schema" "empty_schema"} node-names)))))))++(deftest erd-endpoint-table-ids-are-scoped-to-database-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "table-ids from another database are ignored"+ (mt/with-temp [:model/Database {db-a-id :id} {}+ :model/Table _ {:db_id db-a-id :name "local" :schema "PUBLIC"}+ :model/Database {db-b-id :id} {}+ :model/Table {other-table-id :id} {:db_id db-b-id :name "other" :schema "PUBLIC"}]+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-a-id+ :table-ids other-table-id)]+ (is (empty? (:nodes response)))+ (is (empty? (:edges response))))))))++(deftest erd-endpoint-excludes-hidden-and-sensitive-metadata-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "hidden tables are omitted; all field visibility types are included"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {visible-table-id :id} {:db_id db-id :name "visible" :schema "PUBLIC"}+ :model/Field _ {:table_id visible-table-id :name "visible_id"+ :database_type "INTEGER" :base_type :type/Integer}+ :model/Field _ {:table_id visible-table-id :name "secret"+ :database_type "INTEGER" :base_type :type/Integer+ :visibility_type "sensitive"}+ :model/Field _ {:table_id visible-table-id :name "hidden_field"+ :database_type "INTEGER" :base_type :type/Integer+ :visibility_type "hidden"}+ :model/Field _ {:table_id visible-table-id :name "retired_field"+ :database_type "INTEGER" :base_type :type/Integer+ :visibility_type "retired"}+ :model/Table _ {:db_id db-id :name "hidden_table" :schema "PUBLIC"+ :visibility_type "hidden"}]+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-id+ :schema "PUBLIC")+ node-names (set (map :name (:nodes response)))+ field-names (set (map :name (mapcat :fields (:nodes response))))]+ (is (= #{"visible"} node-names))+ (is (= #{"visible_id" "hidden_field" "secret" "retired_field"} field-names)))))))++(deftest erd-endpoint-does-not-leak-hidden-fk-targets-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "FK targets in hidden tables are nulled and do not produce edges; FKs to sensitive fields resolve"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {hidden-target-table-id :id} {:db_id db-id :name "hidden_target" :schema "PUBLIC"+ :visibility_type "hidden"}+ :model/Field {hidden-target-field-id :id} {:table_id hidden-target-table-id :name "id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK}+ :model/Table {visible-target-table-id :id} {:db_id db-id :name "visible_target" :schema "PUBLIC"}+ :model/Field {sensitive-target-field-id :id} {:table_id visible-target-table-id :name "secret_id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK+ :visibility_type "sensitive"}+ :model/Table {source-table-id :id} {:db_id db-id :name "source" :schema "PUBLIC"}+ :model/Field {hidden-table-fk-id :id} {:table_id source-table-id :name "hidden_target_id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/FK+ :fk_target_field_id hidden-target-field-id}+ :model/Field {sensitive-field-fk-id :id} {:table_id source-table-id :name "sensitive_target_id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/FK+ :fk_target_field_id sensitive-target-field-id}]+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-id+ :schema "PUBLIC")+ nodes-by-name (into {} (map (juxt :name identity)) (:nodes response))+ source-node (get nodes-by-name "source")+ fields-by-id (into {} (map (juxt :id identity)) (:fields source-node))+ hidden-fk (get fields-by-id hidden-table-fk-id)+ sensitive-fk (get fields-by-id sensitive-field-fk-id)]+ (is (not (contains? nodes-by-name "hidden_target")))+ (is (contains? nodes-by-name "visible_target"))+ (testing "FK to a field in a hidden table is nulled and produces no edge"+ (is (nil? (:fk_target_table_id hidden-fk)))+ (is (nil? (:fk_target_field_id hidden-fk)))+ (is (not-any? #(= hidden-table-fk-id (:source_field_id %)) (:edges response))))+ (testing "FK to a sensitive field in a visible table resolves normally"+ (is (= visible-target-table-id (:fk_target_table_id sensitive-fk)))+ (is (= sensitive-target-field-id (:fk_target_field_id sensitive-fk)))+ (is (some #(and (= sensitive-field-fk-id (:source_field_id %))+ (= sensitive-target-field-id (:target_field_id %)))+ (:edges response)))))))))++(deftest erd-endpoint-published-external-fk-target-test+ (mt/with-premium-features #{:schema-viewer :library}+ (testing "published cross-schema FK targets keep target IDs when only readable via collection"+ (mt/with-no-data-perms-for-all-users!+ (mt/with-temp [:model/Collection {coll-id :id} {:type collection/library-data-collection-type}+ :model/PermissionsGroup {gid :id} {}+ :model/Database {db-id :id} {}+ :model/Table {target-table-id :id} {:db_id db-id :name "target" :schema "other"+ :is_published true :collection_id coll-id}+ :model/Field {target-pk-id :id} {:table_id target-table-id :name "id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK}+ :model/Table {source-table-id :id} {:db_id db-id :name "source" :schema "public"+ :is_published true :collection_id coll-id}+ :model/Field {source-fk-id :id} {:table_id source-table-id :name "target_id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/FK+ :fk_target_field_id target-pk-id}]+ (perms/add-user-to-group! (mt/user->id :rasta) gid)+ (perms/grant-collection-read-permissions! gid coll-id)+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-id+ :schema "public")+ nodes-by-name (into {} (map (juxt :name identity)) (:nodes response))+ source-node (get nodes-by-name "source")+ fk-field (first (filter #(= source-fk-id (:id %)) (:fields source-node)))]+ (is (contains? nodes-by-name "source"))+ (is (not (contains? nodes-by-name "target"))+ "cross-schema target should remain off-canvas")+ (is (= target-table-id (:fk_target_table_id fk-field)))+ (is (= target-pk-id (:fk_target_field_id fk-field)))))))))++(deftest erd-endpoint-guard-rails-test+ (testing "without :schema-viewer feature returns 402"+ (mt/with-premium-features #{}+ (mt/user-http-request :rasta :get 402 "ee/erd"+ :database-id (mt/id))))+ (mt/with-premium-features #{:schema-viewer}+ (testing "non-existent database returns 404"+ (mt/user-http-request :rasta :get 404 "ee/erd"+ :database-id Integer/MAX_VALUE))))++;;; ---------------------------------------- Permission graph tests ----------------------------------------++;; These tests verify that the graph topology changes correctly under+;; different permission scenarios. We use with-no-data-perms-for-all-users!+;; to revoke everything, then selectively grant table-level access.++(deftest erd-permissions-unreadable-table-excluded-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "unreadable table is excluded from graph, edges, and FK fields"+ (mt/with-no-data-perms-for-all-users!+ (mt/with-temp [:model/PermissionsGroup {gid :id} {}]+ (perms/add-user-to-group! (mt/user->id :rasta) gid)+ ;; Grant orders only — products is unreachable+ (grant-table-read! gid (mt/id :orders))+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id (mt/id)+ :table-ids (mt/id :orders)+ :table-ids (mt/id :products))]+ (testing "graph shows orders alone, no FK edges"+ (is (= {:orders []}+ (graph-shape response))))+ (testing "no FK field leaks IDs of excluded tables"+ (doseq [field (mapcat :fields (:nodes response))+ :when (:fk_target_table_id field)]+ (is (contains? (set (map :table_id (:nodes response)))+ (:fk_target_table_id field)))))))))))++(deftest erd-permissions-intermediate-table-blocks-expansion-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "unreadable intermediate table blocks FK expansion — downstream tables are not discovered"+ ;; Graph: orders → products, reviews → products+ ;; Grant: orders + reviews + people, deny: products+ ;; orders' FK to products is blocked, reviews' FK to products is blocked+ ;; With orders as focal, products is unreadable so nothing beyond orders+people is found+ (mt/with-no-data-perms-for-all-users!+ (mt/with-temp [:model/PermissionsGroup {gid :id} {}]+ (perms/add-user-to-group! (mt/user->id :rasta) gid)+ (grant-table-read! gid (mt/id :orders))+ (grant-table-read! gid (mt/id :reviews))+ (grant-table-read! gid (mt/id :people))+ ;; products is NOT granted — it's the "intermediate" table+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id (mt/id)+ :table-ids (mt/id :orders))]+ (testing "orders reaches people (readable) but not products (unreadable)"+ (is (= {:orders [:people]+ :people []}+ (graph-shape response))))))))))++(deftest erd-permissions-manage-table-metadata-allows-erd-test+ (mt/with-premium-features #{:schema-viewer}+ (testing "manage-table-metadata is enough because ERD is a metadata view"+ (mt/with-no-data-perms-for-all-users!+ (mt/with-temp [:model/PermissionsGroup {gid :id} {}+ :model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id :name "metadata_only" :schema "PUBLIC"}+ :model/Field _ {:table_id table-id :name "id"+ :database_type "INTEGER" :base_type :type/Integer+ :semantic_type :type/PK}]+ (perms/add-user-to-group! (mt/user->id :rasta) gid)+ (data-perms/set-database-permission! gid db-id :perms/view-data :blocked)+ (data-perms/set-database-permission! gid db-id :perms/create-queries :no)+ (data-perms/set-table-permission! gid table-id :perms/manage-table-metadata :yes)+ (let [response (mt/user-http-request :rasta :get 200 "ee/erd"+ :database-id db-id+ :table-ids table-id)]+ (is (= {:metadata_only []}+ (graph-shape response)))))))))diff --git a/enterprise/frontend/src/metabase-enterprise/api/erd.ts b/enterprise/frontend/src/metabase-enterprise/api/erd.tsnew file mode 100644index 00000000000..90d24eb5ea0--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/api/erd.ts@@ -0,0 +1,19 @@+import type { ErdParams, ErdResponse } from "metabase-types/api";++import { EnterpriseApi } from "./api";+import { listTag } from "./tags";++export const erdApi = EnterpriseApi.injectEndpoints({+ endpoints: (builder) => ({+ getErd: builder.query<ErdResponse, ErdParams>({+ query: (params) => ({+ method: "GET",+ url: "/api/ee/erd",+ params,+ }),+ providesTags: [listTag("erd")],+ }),+ }),+});++export const { useGetErdQuery } = erdApi;diff --git a/enterprise/frontend/src/metabase-enterprise/api/index.ts b/enterprise/frontend/src/metabase-enterprise/api/index.tsindex 88a90d53f05..a5a2ac08a98 100644--- a/enterprise/frontend/src/metabase-enterprise/api/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/index.ts@@ -8,6 +8,7 @@ export * from "./content-translation";export * from "./custom-viz-plugin";export * from "./db-routing";export * from "./dependencies";+export * from "./erd";export * from "./gdrive";export * from "./library";export * from "./metabot";diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.ts b/enterprise/frontend/src/metabase-enterprise/plugins.tsindex c81a6b0ca3f..d92dd272bbe 100644--- a/enterprise/frontend/src/metabase-enterprise/plugins.ts+++ b/enterprise/frontend/src/metabase-enterprise/plugins.ts@@ -37,6 +37,7 @@ import { initializePlugin as initializeRemoteSync } from "./remote_sync";import { initializePlugin as initializeReplacement } from "./replacement";import { initializePlugin as initializeResourceDownloads } from "./resource_downloads";import { initializePlugin as initializeSandboxes } from "./sandboxes";+import { initializePlugin as initializeSchemaViewer } from "./schema_viewer";import { initializePlugin as initializeSecurityCenter } from "./security_center";import { initializePlugin as initializeSemanticSearch } from "./semantic_search";import { initializePlugin as initializeSharing } from "./sharing";@@ -95,6 +96,7 @@ export function initializePlugins() {initializeDatabaseReplication();initializeTableEditing();initializeDependencies();+ initializeSchemaViewer();initializeSecurityCenter();initializeSemanticSearch();initializeTransforms();diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/SchemaViewer.module.css b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/SchemaViewer.module.cssnew file mode 100644index 00000000000..59fdb51fa7c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/SchemaViewer.module.css@@ -0,0 +1,41 @@+.reactFlow {+ width: 100%;+ height: 100%;+ min-height: 500px;+ /* Value used by React Flow for its internal controls */+ --canvas-element-z-index: 5;+ --regular-edge-z-index: 0;+ --selected-edge-z-index: 1;+ --node-z-index: 2;+ --minimap-height: 10rem;++ :global(.react-flow__edges > svg) {+ z-index: var(--regular-edge-z-index);+ }+ /* Position selected edges higher to allow further clicks on selected edge */+ :global(.react-flow__edges > svg:has(> .react-flow__edge.selected)) {+ z-index: var(--selected-edge-z-index);+ }++ :global(.react-flow__minimap) {+ height: var(--minimap-height);+ }+}++.entryInput {+ z-index: var(--canvas-element-z-index);+}++.appSwitcher {+ margin-right: 2.5rem;+ background-color: var(--mb-color-background-secondary);+}++.centerLoader {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ pointer-events: none;+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/SchemaViewer.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/SchemaViewer.tsxnew file mode 100644index 00000000000..f017f0fe9fd--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/SchemaViewer.tsx@@ -0,0 +1,372 @@+import {+ Background,+ Panel,+ ReactFlow,+ type ReactFlowInstance,+ useEdgesState,+ useNodesState,+} from "@xyflow/react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { t } from "ttag";++import { getErrorMessage } from "metabase/api/utils/errors";+import { AppSwitcher } from "metabase/nav/components/AppSwitcher";+import {+ Box,+ Button,+ Group,+ Icon,+ Loader,+ Stack,+ Text,+ useColorScheme,+} from "metabase/ui";+import type {+ ConcreteTableId,+ DatabaseId,+ ErdResponse,+ SchemaName,+} from "metabase-types/api";++import S from "./SchemaViewer.module.css";+import { SchemaViewerContext } from "./SchemaViewerContext";+import { SchemaViewerEdge } from "./components/Edge";+import { SchemaViewerNodeSearch } from "./components/NodeSearch";+import { SchemaPickerInput } from "./components/SchemaPickerInput";+import { SchemaViewerMinimap } from "./components/SchemaViewerMinimap";+import { SelectedNodeInfoPanel } from "./components/SelectedNodeInfoPanel";+import { SchemaViewerTableNode } from "./components/TableNode";+import { FIT_VIEW_OPTIONS, MAX_ZOOM, MIN_ZOOM } from "./constants";+import { useCanvasLayout } from "./hooks/useCanvasLayout";+import { useEdgeHandlers } from "./hooks/useEdgeHandlers";+import { useGraphSync } from "./hooks/useGraphSync";+import { useSchemaViewerZoomMethods } from "./hooks/useSchemaViewerZoomMethods";+import type { SchemaViewerFlowEdge, SchemaViewerFlowNode } from "./types";+import { toFlowGraph } from "./utils";++const NODE_TYPES = {+ schemaViewerTable: SchemaViewerTableNode,+};++const EDGE_TYPES = {+ schemaViewerEdge: SchemaViewerEdge,+};++const PRO_OPTIONS = {+ hideAttribution: true,+};++type SchemaViewerProps = {+ databaseId: DatabaseId | undefined;+ schema: string | undefined;+ data: ErdResponse | undefined;+ isFetching: boolean;+ error: unknown;+ contextKey: `${DatabaseId}__${SchemaName}` | null;+ focalTableId: ConcreteTableId | null;+ onExtraTableIdAdd: (tableId: ConcreteTableId) => void;+};++export function SchemaViewer({+ databaseId,+ schema,+ focalTableId,+ onExtraTableIdAdd,+ contextKey,+ data,+ isFetching,+ error,+}: SchemaViewerProps) {+ const { colorScheme } = useColorScheme();++ const [reactFlowInstance, setReactFlowInstance] = useState<ReactFlowInstance<+ SchemaViewerFlowNode,+ SchemaViewerFlowEdge+ > | null>(null);+ const [nodes, setNodes, onNodesChange] = useNodesState<SchemaViewerFlowNode>(+ [],+ );+ const [edges, setEdges, onEdgesChange] = useEdgesState<SchemaViewerFlowEdge>(+ [],+ );++ const { zoomToNode, zoomToCanvas, cancelZoom } =+ useSchemaViewerZoomMethods(reactFlowInstance);++ // Target table IDs whose FK-expansion fetch is still in flight.+ const [expandingTableIds, setExpandingTableIds] = useState<+ Set<ConcreteTableId>+ >(() => new Set());++ // Without this, dragging a node (which produces a new `nodes` array on+ // every animation frame) would force every TableNode + FieldRow to+ // re-render through `useContext`.+ const visibleTableIdsRef = useRef<Set<ConcreteTableId>>(new Set());+ const visibleTableIds = useMemo(() => {+ const prev = visibleTableIdsRef.current;+ if (prev.size === nodes.length) {+ const hasAllNodes = nodes.every((n) => prev.has(n.data.table_id));+ if (hasAllNodes) {+ return prev;+ }+ }+ const next = new Set<ConcreteTableId>();+ for (const n of nodes) {+ next.add(n.data.table_id);+ }+ visibleTableIdsRef.current = next;+ return next;+ }, [nodes]);++ const [selectedNodeIdIntent, setSelectedNodeId] = useState<string | null>(+ null,+ );+ const selectedNodeId = useMemo(+ () =>+ selectedNodeIdIntent != null &&+ nodes.some((n) => n.id === selectedNodeIdIntent)+ ? selectedNodeIdIntent+ : null,+ [nodes, selectedNodeIdIntent],+ );++ const graph = useMemo(() => {+ if (data == null) {+ return null;+ }+ return toFlowGraph(data);+ }, [data]);++ const hasDbSelected = databaseId != null;+ const { registerPendingExpansion } = useGraphSync({+ hasDbSelected,+ error,+ isFetching,+ graph,+ nodes,+ contextKey,+ setNodes,+ setEdges,+ setExpandingTableIds,+ zoomToNode,+ zoomToCanvas,+ });++ // When the URL pins exactly one table-id from current schema, which happens+ // when user opens Schema Viewer from a table metadata sidebar in Table Details,+ // zoom onto that table once ReactFlow has actually drawn it.+ const focalZoomRef = useRef<{+ contextKey: string;+ focalTableId: ConcreteTableId;+ } | null>(null);++ useEffect(() => {+ if (+ focalTableId == null ||+ schema == null ||+ contextKey == null ||+ nodes.length === 0+ ) {+ return;+ }+ const targetNode = nodes.find((n) => n.data.table_id === focalTableId);+ if (+ targetNode == null ||+ targetNode.data.schema !== schema ||+ targetNode.measured?.width == null+ ) {+ return;+ }+ const done = focalZoomRef.current;+ if (done?.contextKey === contextKey && done.focalTableId === focalTableId) {+ return;+ }+ zoomToNode(targetNode.id);+ focalZoomRef.current = { contextKey, focalTableId };+ }, [focalTableId, schema, contextKey, nodes, zoomToNode]);++ const { resetLayout, focusOnNode } = useCanvasLayout({+ nodes,+ edges,+ setNodes,+ setEdges,+ zoomToNode,+ zoomToCanvas,+ });++ const { handleEdgeClick, clearEdgeSelection } = useEdgeHandlers({+ zoomToNode,+ setNodes,+ setEdges,+ });++ // FK click registers a pending expansion target so graph sync can auto-select the FK+ // edge AND zoom to the new table once the next ERD response merges.+ const handleExpandToTable = useCallback(+ (+ tableId: ConcreteTableId,+ candidateEdgeIdsToSelect?: readonly string[],+ ) => {+ if (databaseId == null) {+ return;+ }+ onExtraTableIdAdd(tableId);+ setExpandingTableIds((prev) => {+ if (prev.has(tableId)) {+ return prev;+ }+ const next = new Set(prev);+ next.add(tableId);+ return next;+ });+ registerPendingExpansion(tableId, candidateEdgeIdsToSelect);+ },+ [+ databaseId,+ onExtraTableIdAdd,+ setExpandingTableIds,+ registerPendingExpansion,+ ],+ );++ const handleClearSelection = useCallback(() => {+ setSelectedNodeId(null);+ }, []);++ const handleSelectNode = useCallback(+ (nodeId: string | null) => {+ setSelectedNodeId(nodeId);+ if (nodeId != null) {+ clearEdgeSelection();+ }+ },+ [clearEdgeSelection],+ );++ const handleSchemaChange = useCallback(() => {+ setSelectedNodeId(null);+ cancelZoom();+ }, [cancelZoom]);++ const schemaViewerContextValue = useMemo(+ () => ({+ visibleTableIds,+ expandingTableIds,+ expandToTable: handleExpandToTable,+ selectedNodeId,+ selectNode: handleSelectNode,+ zoomToNode,+ }),+ [+ visibleTableIds,+ expandingTableIds,+ handleExpandToTable,+ selectedNodeId,+ handleSelectNode,+ zoomToNode,+ ],+ );++ return (+ <SchemaViewerContext.Provider value={schemaViewerContextValue}>+ <ReactFlow+ className={S.reactFlow}+ nodes={nodes}+ edges={edges}+ nodeTypes={NODE_TYPES}+ edgeTypes={EDGE_TYPES}+ proOptions={PRO_OPTIONS}+ minZoom={MIN_ZOOM}+ maxZoom={MAX_ZOOM}+ colorMode={colorScheme === "dark" ? "dark" : "light"}+ fitView+ fitViewOptions={FIT_VIEW_OPTIONS}+ onInit={setReactFlowInstance}+ onNodesChange={onNodesChange}+ onEdgesChange={onEdgesChange}+ onEdgeClick={handleEdgeClick}+ onPaneClick={clearEdgeSelection}+ >+ <Background />+ <SchemaViewerMinimap />++ <Panel className={S.entryInput} position="top-left">+ <Group gap="sm">+ <SchemaPickerInput+ databaseId={databaseId}+ schema={schema}+ onSchemaChange={handleSchemaChange}+ />+ <SchemaViewerNodeSearch key={contextKey ?? ""} nodes={nodes} />+ </Group>+ </Panel>++ <Panel position="top-right">+ <AppSwitcher className={S.appSwitcher} />+ </Panel>++ {nodes.length > 0 && (+ <Panel position="bottom-left">+ <Group gap="sm">+ <Button+ bg="background-primary"+ variant="default"+ leftSection={<Icon name="sparkles" />}+ onClick={resetLayout}+ >+ {t`Auto-layout`}+ </Button>+ {selectedNodeId != null && (+ <Button+ bg="background-primary"+ variant="default"+ onClick={() => focusOnNode(selectedNodeId)}+ >+ {t`Focus node`}+ </Button>+ )}+ </Group>+ </Panel>+ )}++ <SelectedNodeInfoPanel+ nodes={nodes}+ selectedNodeId={selectedNodeId}+ onClose={handleClearSelection}+ />++ {isFetching && expandingTableIds.size === 0 && (+ <Box className={S.centerLoader} data-testid="schema-viewer-loader">+ <Loader />+ </Box>+ )}+ {error != null && (+ <Panel position="bottom-center">+ <Stack+ align="center"+ justify="center"+ mb="xl"+ data-testid="schema-viewer-error"+ >+ <Text c="text-secondary">+ {getErrorMessage(error, t`Failed to load schema.`)}+ </Text>+ </Stack>+ </Panel>+ )}+ {!hasDbSelected && !isFetching && error == null && (+ <Panel position="bottom-center">+ <Stack+ align="center"+ justify="center"+ pt="xl"+ data-testid="schema-viewer-empty-state"+ >+ <Text c="text-tertiary">{t`No schema selected`}</Text>+ </Stack>+ </Panel>+ )}+ </ReactFlow>+ </SchemaViewerContext.Provider>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/SchemaViewerContext.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/SchemaViewerContext.tsxnew file mode 100644index 00000000000..26691926430--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/SchemaViewerContext.tsx@@ -0,0 +1,38 @@+import { createContext, useContext } from "react";++import type { ConcreteTableId } from "metabase-types/api";++type SchemaViewerContextValue = {+ visibleTableIds: Set<ConcreteTableId>;+ /**+ * IDs of tables whose fetch was triggered by an FK-field expansion and has+ * not yet resolved. Field rows use this to show a loader in place of the+ * database type while the new table is being loaded.+ */+ expandingTableIds: Set<ConcreteTableId>;+ expandToTable: (+ tableId: ConcreteTableId,+ /**+ * Edge IDs to try selecting once the new table arrives in the graph.+ * Pass both possible orderings (source-first and target-first) since+ * the backend's source/target convention isn't fixed.+ */+ candidateEdgeIdsToSelect?: readonly string[],+ ) => void;+ selectedNodeId: string | null;+ selectNode: (nodeId: string | null) => void;+ zoomToNode: (nodeId: string) => void;+};++export const SchemaViewerContext = createContext<SchemaViewerContextValue>({+ visibleTableIds: new Set(),+ expandingTableIds: new Set(),+ expandToTable: () => {},+ selectedNodeId: null,+ selectNode: () => {},+ zoomToNode: () => {},+});++export function useSchemaViewerContext() {+ return useContext(SchemaViewerContext);+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/Edge/EdgeSymbol.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/Edge/EdgeSymbol.tsxnew file mode 100644index 00000000000..5194b31c995--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/Edge/EdgeSymbol.tsx@@ -0,0 +1,65 @@+// Crow's foot (many-to-one symbol) geometry constants+const GAP = 4;+const W = 8;+const H = 6;++export type SymbolType = "one" | "many";+type SymbolSide = "source" | "target";++type EdgeSymbolProps = {+ type: SymbolType;+ side: SymbolSide;+ x: number;+ y: number;+ stroke: string;+ strokeWidth: number;+};++export function EdgeSymbol({+ type,+ side,+ x,+ y,+ stroke,+ strokeWidth,+}: EdgeSymbolProps) {+ const anchorX = side === "source" ? x + GAP : x - GAP;+ const backX = side === "source" ? x + GAP + W : x - GAP - W;++ if (type === "one") {+ return (+ <line+ data-testid="schema-viewer-edge-symbol-line"+ x1={anchorX}+ y1={y - H}+ x2={anchorX}+ y2={y + H}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ );+ }++ return (+ <>+ <line+ data-testid="schema-viewer-edge-symbol-line"+ x1={backX}+ y1={y}+ x2={anchorX}+ y2={y - H}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ <line+ data-testid="schema-viewer-edge-symbol-line"+ x1={backX}+ y1={y}+ x2={anchorX}+ y2={y + H}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ </>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/Edge/SchemaViewerEdge.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/Edge/SchemaViewerEdge.tsxnew file mode 100644index 00000000000..62b558f296f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/Edge/SchemaViewerEdge.tsx@@ -0,0 +1,141 @@+import {+ type EdgeProps,+ getSmoothStepPath,+ useNodesInitialized,+} from "@xyflow/react";+import type { CSSProperties } from "react";+import { memo, useMemo } from "react";++import { usePalette } from "metabase/common/hooks/use-palette";++import type { SchemaViewerEdgeData, SchemaViewerFlowEdge } from "../../types";++import { EdgeSymbol, type SymbolType } from "./EdgeSymbol";++/**+ * Builds an SVG path that loops from a source handle on the right side of a+ * table around to a target handle on the same table.+ */+const SELF_REF_OFFSET = 50;+const SELF_REF_RADIUS = 8;+export function getSelfRefEdgePath({+ sourceX,+ sourceY,+ targetX,+ targetY,+}: {+ sourceX: number;+ sourceY: number;+ targetX: number;+ targetY: number;+}): string {+ const midX = Math.max(sourceX, targetX) + SELF_REF_OFFSET;+ const r = SELF_REF_RADIUS;+ const sourceTurn = sourceY < targetY ? r : -r;+ const targetTurn = sourceY < targetY ? -r : r;+ return [+ `M ${sourceX} ${sourceY}`,+ `L ${midX - r} ${sourceY}`,+ `Q ${midX} ${sourceY} ${midX} ${sourceY + sourceTurn}`,+ `L ${midX} ${targetY + targetTurn}`,+ `Q ${midX} ${targetY} ${midX - r} ${targetY}`,+ `L ${targetX} ${targetY}`,+ ].join(" ");+}++function getSymbolTypes(relationship: SchemaViewerEdgeData["relationship"]): {+ source: SymbolType;+ target: SymbolType;+} {+ if (relationship === "one-to-one") {+ return { source: "one", target: "one" };+ }+ return { source: "many", target: "one" };+}++export const SchemaViewerEdge = memo(function SchemaViewerEdge(+ props: EdgeProps<SchemaViewerFlowEdge>,+) {+ const palette = usePalette();+ const isInitialized = useNodesInitialized();+ const isSelfRef = props.source === props.target;+ const isHidden = !isInitialized;+ const selected = props.selected ?? false;++ const relationship = props.data?.relationship ?? "many-to-one";+ const symbols = useMemo(() => getSymbolTypes(relationship), [relationship]);+ const stroke = selected+ ? (palette.brand ?? "var(--mb-color-brand)")+ : (palette["border-strong"] ?? "var(--mb-color-border-strong)");+ const strokeWidth = selected ? 2 : 1;++ const style: CSSProperties = useMemo(+ () => ({+ strokeWidth,+ stroke,+ strokeDasharray: "9 9",+ visibility: isHidden ? "hidden" : undefined,+ }),+ [stroke, strokeWidth, isHidden],+ );++ let edgePath: string;++ if (isSelfRef) {+ edgePath = getSelfRefEdgePath({+ sourceX: props.sourceX,+ sourceY: props.sourceY,+ targetX: props.targetX,+ targetY: props.targetY,+ });+ } else {+ [edgePath] = getSmoothStepPath({+ sourceX: props.sourceX,+ sourceY: props.sourceY,+ sourcePosition: props.sourcePosition,+ targetX: props.targetX,+ targetY: props.targetY,+ targetPosition: props.targetPosition,+ });+ }++ return (+ <>+ {/* Invisible wide hit-area path so clicks on thin edges are easy */}+ <path+ d={edgePath}+ fill="none"+ stroke="transparent"+ strokeWidth={20}+ style={isHidden ? { visibility: "hidden" as const } : undefined}+ />+ <path+ data-testid="schema-viewer-edge-path"+ data-selected={selected ? "true" : undefined}+ d={edgePath}+ fill="none"+ style={style}+ />+ {!isHidden && (+ <g data-testid="schema-viewer-edge-symbols">+ <EdgeSymbol+ side="source"+ type={symbols.source}+ x={props.sourceX}+ y={props.sourceY}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ <EdgeSymbol+ side={isSelfRef ? "source" : "target"}+ type={symbols.target}+ x={props.targetX}+ y={props.targetY}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ </g>+ )}+ </>+ );+});diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/Edge/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/Edge/index.tsnew file mode 100644index 00000000000..ddecc733888--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/Edge/index.ts@@ -0,0 +1 @@+export { SchemaViewerEdge } from "./SchemaViewerEdge";diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/SchemaViewerNodeSearch.module.css b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/SchemaViewerNodeSearch.module.cssnew file mode 100644index 00000000000..b8382dbe06c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/SchemaViewerNodeSearch.module.css@@ -0,0 +1,23 @@+.options {+ padding: 0.5rem;+}++.listItem {+ height: 2.25rem;+ min-height: 2.25rem;+ padding: 0.5rem;+ border-radius: var(--default-border-radius);+}++.label {+ flex: 1 1 0;+ min-width: 0;+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.fieldCount {+ flex-shrink: 0;+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/SchemaViewerNodeSearch.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/SchemaViewerNodeSearch.tsxnew file mode 100644index 00000000000..5995293a524--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/SchemaViewerNodeSearch.tsx@@ -0,0 +1,179 @@+import { useHotkeys } from "@mantine/hooks";+import { useMemo, useRef, useState } from "react";+import { t } from "ttag";++import {+ Combobox,+ FixedSizeIcon,+ Group,+ Text,+ TextInput,+ useCombobox,+} from "metabase/ui";+import * as Lib from "metabase-lib";++import { useSchemaViewerContext } from "../../SchemaViewerContext";+import type { SchemaViewerFlowNode } from "../../types";++import S from "./SchemaViewerNodeSearch.module.css";++type SchemaViewerNodeSearchProps = {+ nodes: SchemaViewerFlowNode[];+};++type SearchItem = {+ id: string;+ label: React.ReactNode;+ text: string;+ fkCount: number;+ haystack: string[];+};++export function SchemaViewerNodeSearch({ nodes }: SchemaViewerNodeSearchProps) {+ const { zoomToNode } = useSchemaViewerContext();+ const inputRef = useRef<HTMLInputElement>(null);+ const [query, setQuery] = useState("");++ const combobox = useCombobox({+ onDropdownClose: () => combobox.resetSelectedOption(),+ onDropdownOpen: () => combobox.updateSelectedOptionIndex("active"),+ });++ useHotkeys([+ [+ "f",+ () => {+ inputRef.current?.focus();+ inputRef.current?.select();+ combobox.openDropdown();+ },+ ],+ ]);++ const allItems = useMemo<SearchItem[]>(+ () =>+ nodes.map((node) => {+ const { name, display_name, fields } = node.data;+ const label = formatTableLabel(name, display_name);+ const text = formatTableLabelText(name, display_name);+ const fkCount = fields.filter((f) =>+ Lib.isForeignKey(Lib.legacyColumnTypeInfo(f)),+ ).length;+ return {+ id: node.id,+ label,+ text,+ fkCount,+ haystack: [text, name, display_name ?? ""]+ .filter(Boolean)+ .map((s) => s.toLowerCase()),+ };+ }),+ [nodes],+ );++ const filteredItems = useMemo(() => {+ const q = query.trim().toLowerCase();+ if (q === "") {+ return allItems;+ }+ return allItems.filter((item) => item.haystack.some((h) => h.includes(q)));+ }, [allItems, query]);++ const handleOptionSubmit = (nodeId: string) => {+ const item = allItems.find((i) => i.id === nodeId);+ if (item == null) {+ return;+ }+ zoomToNode(item.id);+ setQuery(item.text);+ combobox.closeDropdown();+ inputRef.current?.blur();+ };++ if (nodes.length === 0) {+ return null;+ }++ return (+ <Combobox+ store={combobox}+ withinPortal={false}+ onOptionSubmit={handleOptionSubmit}+ >+ <Combobox.Target>+ <TextInput+ ref={inputRef}+ leftSection={<FixedSizeIcon name="search" />}+ placeholder={t`Jump to table`}+ value={query}+ w="20rem"+ data-testid="schema-viewer-node-search-input"+ onChange={(event) => {+ setQuery(event.currentTarget.value);+ combobox.openDropdown();+ combobox.updateSelectedOptionIndex();+ }}+ onFocus={() => {+ setQuery("");+ combobox.openDropdown();+ }}+ onBlur={() => combobox.closeDropdown()}+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ combobox.closeDropdown();+ inputRef.current?.blur();+ }+ }}+ />+ </Combobox.Target>+ <Combobox.Dropdown p={0} data-testid="schema-viewer-node-search-dropdown">+ {filteredItems.length === 0 ? (+ <Combobox.Empty>{t`No tables found`}</Combobox.Empty>+ ) : (+ <Combobox.Options className={S.options}>+ {filteredItems.map((item) => (+ <Combobox.Option+ value={item.id}+ key={item.id}+ className={S.listItem}+ >+ <Group gap="sm" wrap="nowrap" justify="space-between" w="100%">+ <Text className={S.label}>{item.label}</Text>+ <Group gap="xs" wrap="nowrap" className={S.fieldCount}>+ <Text c="text-tertiary" fz="xs">+ {item.fkCount}+ </Text>+ <FixedSizeIcon+ name="connections"+ c="text-tertiary"+ size={12}+ />+ </Group>+ </Group>+ </Combobox.Option>+ ))}+ </Combobox.Options>+ )}+ </Combobox.Dropdown>+ </Combobox>+ );+}++function formatTableLabel(name: string, displayName: string | undefined) {+ if (displayName && displayName !== name) {+ return (+ <>+ <span style={{ fontWeight: "bold" }}>{name}</span> ({displayName})+ </>+ );+ }+ return name;+}++function formatTableLabelText(name: string, displayName: string | undefined) {+ if (displayName && displayName !== name) {+ return `${name} (${displayName})`;+ }+ return name;+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/SchemaViewerNodeSearch.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/SchemaViewerNodeSearch.unit.spec.tsxnew file mode 100644index 00000000000..a0a02a35336--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/SchemaViewerNodeSearch.unit.spec.tsx@@ -0,0 +1,146 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen, within } from "__support__/ui";+import { checkNotNull } from "metabase/utils/types";+import type { ConcreteTableId } from "metabase-types/api";++import { SchemaViewerContext } from "../../SchemaViewerContext";+import type { SchemaViewerFlowNode } from "../../types";+import { type FlowNodeFieldSpec, makeFlowNode } from "../../utils/test-utils";++import { SchemaViewerNodeSearch } from "./SchemaViewerNodeSearch";++// NodeSearch only reads a node's id, name, and field list — the size/opacity+// values just need to look like a rendered node, hence the fixed style.+function makeNode(+ id: number,+ name: string,+ fields: FlowNodeFieldSpec[] = [],+): SchemaViewerFlowNode {+ return makeFlowNode({+ id,+ name,+ fields,+ width: 320,+ height: 200,+ opacity: 1,+ });+}++type SetupOpts = {+ nodes?: SchemaViewerFlowNode[];+ zoomToNode?: jest.Mock;+};++function setup({+ nodes = [+ makeNode(1, "ORDERS", [{ name: "user_id", isFK: true }, { name: "qty" }]),+ makeNode(2, "PRODUCTS"),+ makeNode(3, "REVIEWS", [{ name: "order_id", isFK: true }]),+ ],+}: SetupOpts = {}) {+ const zoomToNode = jest.fn();+ const value = {+ visibleTableIds: new Set<ConcreteTableId>(),+ expandingTableIds: new Set<ConcreteTableId>(),+ expandToTable: jest.fn(),+ selectedNodeId: null,+ selectNode: jest.fn(),+ zoomToNode,+ };++ const utils = renderWithProviders(+ <SchemaViewerContext.Provider value={value}>+ <SchemaViewerNodeSearch nodes={nodes} />+ </SchemaViewerContext.Provider>,+ );++ return { ...utils, zoomToNode };+}++describe("SchemaViewerNodeSearch", () => {+ it("renders no search input when there are no nodes", () => {+ setup({ nodes: [] });+ expect(+ screen.queryByPlaceholderText(/Jump to table/i),+ ).not.toBeInTheDocument();+ });++ it("renders the search input when nodes exist", () => {+ setup();+ expect(screen.getByPlaceholderText(/Jump to table/i)).toBeInTheDocument();+ });++ it("filters options by name (case-insensitive substring)", async () => {+ setup();+ await userEvent.click(screen.getByPlaceholderText(/Jump to table/i));+ await userEvent.type(screen.getByPlaceholderText(/Jump to table/i), "ord");+ expect(screen.getByText("ORDERS")).toBeInTheDocument();+ expect(screen.queryByText("PRODUCTS")).not.toBeInTheDocument();+ });++ it("shows 'No tables found' when no option matches", async () => {+ setup();+ await userEvent.click(screen.getByPlaceholderText(/Jump to table/i));+ await userEvent.type(+ screen.getByPlaceholderText(/Jump to table/i),+ "zzz_no_match",+ );+ expect(screen.getByText("No tables found")).toBeInTheDocument();+ });++ it("each option shows the FK count", async () => {+ setup();+ await userEvent.click(screen.getByPlaceholderText(/Jump to table/i));+ // ORDERS has 1 FK; REVIEWS has 1 FK; PRODUCTS has 0 — the FK count+ // appears as text inside the same option row as the table name.+ const options = screen.getAllByRole("option");+ const ordersOption = options.find((opt) =>+ within(opt).queryByText("ORDERS"),+ );+ const reviewsOption = options.find((opt) =>+ within(opt).queryByText("REVIEWS"),+ );+ const productsOption = options.find((opt) =>+ within(opt).queryByText("PRODUCTS"),+ );+ expect(+ within(checkNotNull(ordersOption)).getByText("1"),+ ).toBeInTheDocument();+ expect(+ within(checkNotNull(reviewsOption)).getByText("1"),+ ).toBeInTheDocument();+ expect(+ within(checkNotNull(productsOption)).getByText("0"),+ ).toBeInTheDocument();+ });++ it("selecting an option calls zoomToNode and closes the dropdown", async () => {+ const { zoomToNode } = setup();+ await userEvent.click(screen.getByPlaceholderText(/Jump to table/i));+ await userEvent.click(screen.getByText("ORDERS"));+ expect(zoomToNode).toHaveBeenCalledWith("table-1");+ expect(screen.queryByRole("option")).not.toBeInTheDocument();+ });++ it("Esc closes the dropdown", async () => {+ setup();+ const input = screen.getByPlaceholderText(/Jump to table/i);+ await userEvent.click(input);+ expect(screen.getAllByRole("option").length).toBeGreaterThan(0);+ await userEvent.type(input, "{Escape}");+ expect(screen.queryByRole("option")).not.toBeInTheDocument();+ });++ it("'f' key focuses the input and opens the dropdown", async () => {+ setup();+ const input = screen.getByPlaceholderText(/Jump to table/i);+ expect(input).not.toHaveFocus();+ expect(screen.queryByRole("option")).not.toBeInTheDocument();++ await userEvent.keyboard("f");++ expect(input).toHaveFocus();+ expect(screen.getAllByRole("option").length).toBeGreaterThan(0);+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/index.tsnew file mode 100644index 00000000000..88f4d68bba8--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/NodeSearch/index.ts@@ -0,0 +1 @@+export { SchemaViewerNodeSearch } from "./SchemaViewerNodeSearch";diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/SchemaPickerInput.module.css b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/SchemaPickerInput.module.cssnew file mode 100644index 00000000000..7d0114b0ad2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/SchemaPickerInput.module.css@@ -0,0 +1,20 @@+.triggerButton {+ &:hover {+ background-color: var(--mb-color-background-secondary);+ }+}++.listItem {+ padding: 0.5rem;+ border-radius: var(--default-border-radius);++ &:hover {+ background-color: var(--mb-color-background-hover);+ }+}++.divider {+ height: 1px;+ margin: 0.25rem 0;+ background-color: var(--mb-color-border);+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/SchemaPickerInput.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/SchemaPickerInput.tsxnew file mode 100644index 00000000000..58307084756--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/SchemaPickerInput.tsx@@ -0,0 +1,90 @@+import { useCallback, useState } from "react";+import { push } from "react-router-redux";+import { t } from "ttag";++import { MiniPicker } from "metabase/common/components/Pickers/MiniPicker";+import type { MiniPickerPickableItem } from "metabase/common/components/Pickers/MiniPicker/types";+import { useDispatch } from "metabase/redux";+import { Button, FixedSizeIcon, Text } from "metabase/ui";+import * as Urls from "metabase/urls";+import type { DatabaseId, SchemaName } from "metabase-types/api";++import S from "./SchemaPickerInput.module.css";++type SchemaPickerInputProps = {+ databaseId: DatabaseId | undefined;+ schema: SchemaName | undefined;+ onSchemaChange: () => void;+};++export function SchemaPickerInput({+ databaseId,+ schema,+ onSchemaChange,+}: SchemaPickerInputProps) {+ const dispatch = useDispatch();+ const [opened, setOpened] = useState(databaseId == null);++ const handleChange = useCallback(+ (picked: MiniPickerPickableItem) => {+ // We restrict to `models: ["schema"]`, but the union is wider so we need to add a guard.+ if (picked.model !== "schema") {+ return;+ }+ onSchemaChange();+ dispatch(+ push(+ Urls.dataStudioSchemaViewer({+ databaseId: picked.database_id,+ schema: picked.name,+ }),+ ),+ );+ setOpened(false);+ },+ [dispatch, onSchemaChange],+ );++ const hasSchema = schema != null && schema.length > 0;++ return (+ <MiniPicker+ opened={opened}+ onClose={() => setOpened(false)}+ models={["schema"]}+ onChange={handleChange}+ menuProps={{+ // This allows to toggle menu by clicking the trigger button.+ onChange: setOpened,+ clickOutsideEvents: ["pointerdown", "touchstart"],+ position: "bottom-start",+ }}+ >+ <Button+ variant="default"+ className={S.triggerButton}+ leftSection={+ <FixedSizeIcon+ name="database"+ c={hasSchema ? undefined : "text-tertiary"}+ />+ }+ rightSection={+ <FixedSizeIcon+ name="chevrondown"+ c={hasSchema ? undefined : "text-tertiary"}+ />+ }+ data-testid="schema-picker-button"+ >+ {hasSchema ? (+ schema+ ) : (+ <Text c="text-secondary" fw={700}>+ {t`Pick a schema to view`}+ </Text>+ )}+ </Button>+ </MiniPicker>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/index.tsnew file mode 100644index 00000000000..534e18c732b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/index.ts@@ -0,0 +1 @@+export { SchemaPickerInput } from "./SchemaPickerInput";diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaViewerMinimap.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaViewerMinimap.tsxnew file mode 100644index 00000000000..30529f6ca37--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaViewerMinimap.tsx@@ -0,0 +1,63 @@+import { MiniMap, useEdges } from "@xyflow/react";+import { useCallback, useMemo } from "react";++import { useColorScheme } from "metabase/ui";++const LIGHT_LEAF_LIGHTNESS = 88;+const LIGHT_HUB_LIGHTNESS = 32;+const DARK_LEAF_LIGHTNESS = 28;+const DARK_HUB_LIGHTNESS = 80;++/**+ * MiniMap shades each node by its edge count: hubs (more connections)+ * read as the more-prominent end of the gradient, leaves as the less-prominent+ * end. Counts are normalized against the most-connected node.+ */+export function SchemaViewerMinimap() {+ const edges = useEdges();+ const { colorScheme } = useColorScheme();+ const isDark = colorScheme === "dark";++ const connectionCounts = useMemo(() => {+ const counts = new Map<string, number>();+ for (const edge of edges) {+ counts.set(edge.source, (counts.get(edge.source) ?? 0) + 1);+ if (edge.target !== edge.source) {+ counts.set(edge.target, (counts.get(edge.target) ?? 0) + 1);+ }+ }+ return counts;+ }, [edges]);++ const maxConnectionCount = useMemo(+ () => Math.max(0, ...connectionCounts.values()),+ [connectionCounts],+ );++ const nodeColor = useCallback(+ (node: { id: string }) => {+ const count = connectionCounts.get(node.id) ?? 0;+ const ratio = maxConnectionCount > 0 ? count / maxConnectionCount : 0;+ const leaf = isDark ? DARK_LEAF_LIGHTNESS : LIGHT_LEAF_LIGHTNESS;+ const hub = isDark ? DARK_HUB_LIGHTNESS : LIGHT_HUB_LIGHTNESS;+ const lightness = leaf + ratio * (hub - leaf);+ return `hsl(0, 0%, ${lightness}%)`;+ },+ [connectionCounts, maxConnectionCount, isDark],+ );++ return (+ <MiniMap+ position="bottom-right"+ pannable+ zoomable={false}+ nodeColor={nodeColor}+ bgColor={+ isDark+ ? "var(--mb-color-background-secondary)"+ : "var(--mb-color-background)"+ }+ maskStrokeColor="var(--mb-color-border)"+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/InfoPanelField.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/InfoPanelField.tsxnew file mode 100644index 00000000000..eb31071f8da--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/InfoPanelField.tsx@@ -0,0 +1,118 @@+import cx from "classnames";+import { t } from "ttag";++import { getColumnIcon } from "metabase/common/utils/columns";+import CS from "metabase/css/core/index.css";+import {+ Ellipsified,+ FixedSizeIcon,+ Group,+ Loader,+ Text,+ Tooltip,+ UnstyledButton,+} from "metabase/ui";+import * as Lib from "metabase-lib";+import type { ErdField } from "metabase-types/api";++import type { SchemaViewerFlowNode } from "../../types";++import S from "./SelectedNodeInfoPanel.module.css";++type InfoPanelFieldProps = {+ field: ErdField;+ targetNode: SchemaViewerFlowNode | null;+ isExpanding: boolean;+ selectedNode: SchemaViewerFlowNode | null;+ onFetchExternal: () => void;+ onZoomToNode: (nodeId: string) => void;+};++export function InfoPanelField({+ field,+ targetNode,+ isExpanding,+ selectedNode,+ onFetchExternal,+ onZoomToNode,+}: InfoPanelFieldProps) {+ const fieldIcon = getColumnIcon(+ Lib.legacyColumnTypeInfo({+ base_type: field.base_type,+ effective_type: field.effective_type ?? undefined,+ semantic_type: field.semantic_type,+ }),+ );+ const isExternalFk = field.fk_target_table_id != null && targetNode == null;++ const fieldName = (+ <Ellipsified className={S.fieldName}>{field.name}</Ellipsified>+ );++ return (+ <Group className={cx(S.fieldRow, CS.textWrap)} gap="sm" wrap="nowrap">+ <FixedSizeIcon name={fieldIcon} c="text-secondary" />+ {isExternalFk ? (+ <Tooltip label={t`Fetch external table`} disabled={isExpanding}>+ <UnstyledButton+ className={S.fkLink}+ c="brand"+ disabled={isExpanding}+ onClick={onFetchExternal}+ flex="1 1 auto"+ lh={1}+ h="100%"+ style={{ overflow: "visible" }}+ >+ {fieldName}+ </UnstyledButton>+ </Tooltip>+ ) : (+ fieldName+ )}+ {isExpanding && (+ <Loader size="xs" data-testid="schema-viewer-info-panel-fetch-loader" />+ )}+ {targetNode != null && (+ <Group+ gap="xs"+ wrap="nowrap"+ flex="1 1 auto"+ h="100%"+ miw={0}+ maw="50%"+ >+ <Text c="text-tertiary" lh={1} fz="1rem">+ →+ </Text>+ <UnstyledButton+ className={S.fkLink}+ c="brand"+ onClick={() => onZoomToNode(targetNode.id)}+ >+ <Group align="end" gap={4} flex="0 0 auto" wrap="nowrap" w="100%">+ <FixedSizeIcon name="table" size={14} />+ <Ellipsified>+ {formatTargetTableName(selectedNode, targetNode)}+ </Ellipsified>+ </Group>+ </UnstyledButton>+ </Group>+ )}+ </Group>+ );+}++function formatTargetTableName(+ selectedNode: SchemaViewerFlowNode | null,+ targetNode: SchemaViewerFlowNode,+): string {+ const targetName = targetNode.data.name;+ const targetSchema = targetNode.data.schema;+ const sourceSchema = selectedNode?.data.schema ?? null;+ const isExternalSchema =+ targetSchema != null &&+ targetSchema !== "" &&+ targetSchema !== sourceSchema;+ return isExternalSchema ? `${targetSchema}.${targetName}` : targetName;+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelBody/PanelBody.module.css b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelBody/PanelBody.module.cssnew file mode 100644index 00000000000..5c0eabed174--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelBody/PanelBody.module.css@@ -0,0 +1,5 @@+.body {+ flex: 1 1 auto;+ min-height: 0;+ overflow: auto;+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelBody/PanelBody.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelBody/PanelBody.tsxnew file mode 100644index 00000000000..67a8049f23a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelBody/PanelBody.tsx@@ -0,0 +1,119 @@+import { useMemo } from "react";+import { msgid, ngettext, t } from "ttag";++import CS from "metabase/css/core/index.css";+import { Box, Stack, Text, Title } from "metabase/ui";+import { getUserName } from "metabase/utils/user";+import type { ConcreteTableId } from "metabase-types/api";++import { useSchemaViewerContext } from "../../../SchemaViewerContext";+import type { SchemaViewerFlowNode } from "../../../types";+import { getEdgeId } from "../../../utils";+import { InfoPanelField } from "../InfoPanelField";++import S from "./PanelBody.module.css";++type PanelBodyProps = {+ node: SchemaViewerFlowNode;+ nodes: SchemaViewerFlowNode[];+};++export function PanelBody({ node, nodes }: PanelBodyProps) {+ return (+ <Stack className={S.body} p="lg" gap="lg">+ <DescriptionSection node={node} />+ <OwnerSection node={node} />+ <FieldsSection node={node} nodes={nodes} />+ </Stack>+ );+}++type SectionProps = { node: SchemaViewerFlowNode };++function DescriptionSection({ node }: SectionProps) {+ const description = node.data.description ?? "";+ return (+ <Box+ className={CS.textWrap}+ c={description ? "text-primary" : "text-secondary"}+ lh="h4"+ >+ {description.length > 0 ? description : t`No description`}+ </Box>+ );+}++function OwnerSection({ node }: SectionProps) {+ const owner = node.data.owner;+ return (+ <Stack gap="xs" lh="1rem">+ <Title order={6}>{t`Owner`}</Title>+ {owner != null ? (+ <Text lh="h4">{getUserName(owner)}</Text>+ ) : (+ <Text lh="h4" c="text-secondary">{t`No owner`}</Text>+ )}+ </Stack>+ );+}++function FieldsSection({ node, nodes }: PanelBodyProps) {+ const { zoomToNode, expandToTable, expandingTableIds } =+ useSchemaViewerContext();++ const nodesByTableId = useMemo(() => {+ const map = new Map<ConcreteTableId, SchemaViewerFlowNode>();+ for (const n of nodes) {+ map.set(n.data.table_id, n);+ }+ return map;+ }, [nodes]);++ const fields = node.data.fields;+ const count = fields.length;+ return (+ <Stack gap="md" lh="1rem">+ <Title className={CS.textWrap} order={6}>+ {ngettext(msgid`${count} field`, `${count} fields`, count)}+ </Title>+ {fields.map((field) => {+ const targetNode =+ field.fk_target_table_id != null+ ? (nodesByTableId.get(field.fk_target_table_id) ?? null)+ : null;+ const isExternalFk =+ field.fk_target_table_id != null && targetNode == null;+ const isExpanding =+ isExternalFk &&+ field.fk_target_table_id != null &&+ expandingTableIds.has(field.fk_target_table_id);++ const handleFetchExternal = () => {+ if (field.fk_target_table_id == null) {+ return;+ }+ const candidateEdgeIds =+ field.fk_target_field_id != null+ ? [+ getEdgeId(field.id, field.fk_target_field_id),+ getEdgeId(field.fk_target_field_id, field.id),+ ]+ : undefined;+ expandToTable(field.fk_target_table_id, candidateEdgeIds);+ };++ return (+ <InfoPanelField+ key={field.id}+ field={field}+ targetNode={targetNode}+ isExpanding={isExpanding}+ selectedNode={node}+ onFetchExternal={handleFetchExternal}+ onZoomToNode={zoomToNode}+ />+ );+ })}+ </Stack>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelBody/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelBody/index.tsnew file mode 100644index 00000000000..01d44bb3bfd--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelBody/index.ts@@ -0,0 +1 @@+export * from "./PanelBody";diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelHeader/PanelHeader.module.css b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelHeader/PanelHeader.module.cssnew file mode 100644index 00000000000..d911df0e597--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelHeader/PanelHeader.module.css@@ -0,0 +1,20 @@+.root {+ border-bottom: 1px solid var(--mb-color-border);+}++.titleButton {+ display: inline-block;++ &:hover {+ text-decoration: underline;+ }+}++.breadcrumbLink {+ color: var(--mb-color-text-secondary);++ &:hover {+ color: var(--mb-color-brand);+ text-decoration: none;+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelHeader/PanelHeader.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelHeader/PanelHeader.tsxnew file mode 100644index 00000000000..33c168f4b87--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelHeader/PanelHeader.tsx@@ -0,0 +1,130 @@+import cx from "classnames";+import { Fragment } from "react";+import { Link } from "react-router";+import { t } from "ttag";++import { ForwardRefLink } from "metabase/common/components/Link";+import CS from "metabase/css/core/index.css";+import {+ ActionIcon,+ Box,+ Center,+ FixedSizeIcon,+ Group,+ Stack,+ Title,+ Tooltip,+ UnstyledButton,+} from "metabase/ui";+import * as Urls from "metabase/urls";+import type { Database } from "metabase-types/api";++import type { SchemaViewerFlowNode } from "../../../types";++import S from "./PanelHeader.module.css";++type PanelHeaderProps = {+ node: SchemaViewerFlowNode;+ database: Database | undefined;+ onClose: () => void;+ onTitleClick?: () => void;+};++export function PanelHeader({+ node,+ database,+ onClose,+ onTitleClick,+}: PanelHeaderProps) {+ const breadcrumbs = getBreadcrumbs(node, database);+ const metadataUrl = Urls.dataStudioData({+ databaseId: node.data.db_id,+ schemaName: node.data.schema ?? undefined,+ tableId: node.data.table_id,+ });++ const title = (+ <Title className={CS.textWrap} order={3} lh="1.5rem">+ {node.data.name}+ </Title>+ );++ return (+ <Group className={S.root} p="lg" gap="0.75rem" wrap="nowrap">+ <Center w="2.75rem" h="2.75rem" bdrs="50%" bg="background-secondary">+ <FixedSizeIcon name="table" c="brand" size={20} />+ </Center>+ <Stack gap="xs" flex={1}>+ {onTitleClick != null ? (+ <UnstyledButton className={S.titleButton} onClick={onTitleClick}>+ {title}+ </UnstyledButton>+ ) : (+ title+ )}+ {breadcrumbs.length > 0 && (+ <Group c="text-secondary" gap="sm" wrap="nowrap">+ <Group fz="sm" gap="xs">+ {breadcrumbs.map((link, index) => (+ <Fragment key={index}>+ {index > 0 && <Box>/</Box>}+ <Box+ className={cx(S.breadcrumbLink, CS.textWrap)}+ component={Link}+ to={link.url}+ target="_blank"+ lh="1rem"+ >+ {link.label}+ </Box>+ </Fragment>+ ))}+ </Group>+ </Group>+ )}+ </Stack>+ <Group m="-sm" gap="xs" wrap="nowrap">+ <Tooltip label={t`View metadata`}>+ <ActionIcon+ component={ForwardRefLink}+ to={metadataUrl}+ target="_blank"+ aria-label={t`View metadata`}+ >+ <FixedSizeIcon name="external" />+ </ActionIcon>+ </Tooltip>+ <ActionIcon aria-label={t`Close`} onClick={onClose}>+ <FixedSizeIcon name="close" />+ </ActionIcon>+ </Group>+ </Group>+ );+}++type BreadcrumbLink = { label: string; url: string };++function getBreadcrumbs(+ node: SchemaViewerFlowNode,+ database: Database | undefined,+): BreadcrumbLink[] {+ if (database == null) {+ return [];+ }+ const links: BreadcrumbLink[] = [+ {+ label: database.name,+ url: Urls.dataStudioData({ databaseId: node.data.db_id }),+ },+ ];+ if (node.data.schema != null) {+ links.push({+ label: node.data.schema,+ url: Urls.dataStudioData({+ databaseId: node.data.db_id,+ schemaName: node.data.schema,+ }),+ });+ }+ return links;+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelHeader/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelHeader/index.tsnew file mode 100644index 00000000000..40b8fa71048--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/PanelHeader/index.ts@@ -0,0 +1 @@+export * from "./PanelHeader";diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/SelectedNodeInfoPanel.module.css b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/SelectedNodeInfoPanel.module.cssnew file mode 100644index 00000000000..0b98ebcc442--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/SelectedNodeInfoPanel.module.css@@ -0,0 +1,41 @@+.infoPanel {+ position: absolute;+ top: 1rem;+ bottom: 1rem;+ max-height: calc(100% - var(--minimap-height));+ z-index: var(--canvas-element-z-index);++ .card {+ display: flex;+ flex-direction: column;+ padding: 0;+ width: 32rem;+ max-height: 100%;+ pointer-events: all;+ }++ .fieldRow {+ overflow: hidden;+ }++ .fkLink {+ overflow: hidden;+ line-height: 1;++ &:hover span {+ text-decoration: underline;+ }+ }++ .fieldName,+ .targetName {+ flex: 0 1 auto;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .fieldName {+ max-width: 50%;+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/SelectedNodeInfoPanel.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/SelectedNodeInfoPanel.tsxnew file mode 100644index 00000000000..b77cad9b5c3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/SelectedNodeInfoPanel.tsx@@ -0,0 +1,72 @@+import { Panel } from "@xyflow/react";+import { useCallback, useMemo } from "react";++import { useListDatabasesQuery } from "metabase/api";+import { Card } from "metabase/ui";++import { useSchemaViewerContext } from "../../SchemaViewerContext";+import type { SchemaViewerFlowNode } from "../../types";++import { PanelBody } from "./PanelBody";+import { PanelHeader } from "./PanelHeader";+import S from "./SelectedNodeInfoPanel.module.css";++type SelectedNodeInfoPanelProps = {+ nodes: SchemaViewerFlowNode[];+ selectedNodeId: string | null;+ onClose: () => void;+};++export function SelectedNodeInfoPanel({+ nodes,+ selectedNodeId,+ onClose,+}: SelectedNodeInfoPanelProps) {+ const { zoomToNode } = useSchemaViewerContext();++ const { data: databasesResponse } = useListDatabasesQuery({+ include: "schemas",+ });++ const selectedNode = useMemo(+ () =>+ selectedNodeId != null+ ? (nodes.find((n) => n.id === selectedNodeId) ?? null)+ : null,+ [nodes, selectedNodeId],+ );++ const database = useMemo(+ () =>+ selectedNode != null+ ? databasesResponse?.data?.find(+ (db) => db.id === selectedNode.data.db_id,+ )+ : undefined,+ [selectedNode, databasesResponse],+ );++ const handleTitleClick = useCallback(() => {+ if (selectedNode != null) {+ zoomToNode(selectedNode.id);+ }+ }, [selectedNode, zoomToNode]);++ if (selectedNode == null) {+ return null;+ }++ return (+ <Panel className={S.infoPanel} position="top-right">+ <Card className={S.card} withBorder data-testid="graph-info-panel">+ <PanelHeader+ node={selectedNode}+ database={database}+ onClose={onClose}+ onTitleClick={handleTitleClick}+ />+ <PanelBody node={selectedNode} nodes={nodes} />+ </Card>+ </Panel>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/index.tsnew file mode 100644index 00000000000..cd2aaceb4c7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SelectedNodeInfoPanel/index.ts@@ -0,0 +1 @@+export { SelectedNodeInfoPanel } from "./SelectedNodeInfoPanel";diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerFieldRow.module.css b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerFieldRow.module.cssnew file mode 100644index 00000000000..1b9dff92432--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerFieldRow.module.css@@ -0,0 +1,50 @@+.row {+ position: relative;+ white-space: nowrap;+ border-bottom: 1px solid var(--mb-color-border);++ &:last-child {+ border-bottom: none;+ }++ &[data-clickable]:hover {+ background-color: var(--mb-color-background-hover);+ }++ &[data-clickable] .icon,+ &[data-clickable] .clickableName {+ color: var(--mb-color-brand);+ }+}++.icon {+ color: var(--mb-color-text-secondary);+}++.name {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+}++.handle {+ width: 1px;+ height: 1px;+ background: transparent;+ border: none;+ opacity: 0;+}++.expandIndicator {+ position: absolute;+ right: 0;+ top: 50%;+ transform: translate(50%, -50%);+ width: 0.675rem;+ height: 0.675rem;+ border-radius: 50%;+ background: var(--mb-color-white);+ border: 1px solid var(--node-border-color, var(--mb-color-border));+ pointer-events: none;+ z-index: 1;+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerFieldRow.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerFieldRow.tsxnew file mode 100644index 00000000000..333a1994a10--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerFieldRow.tsx@@ -0,0 +1,180 @@+import { Handle, Position, useReactFlow } from "@xyflow/react";+import cx from "classnames";++import { getColumnIcon } from "metabase/common/utils/columns";+import { Box, FixedSizeIcon, Group, Loader } from "metabase/ui";+import * as Lib from "metabase-lib";+import type { ErdField, IconName } from "metabase-types/api";++import { useSchemaViewerContext } from "../../SchemaViewerContext";+import { ROW_HEIGHT_PX } from "../../constants";+import type { SchemaViewerFlowEdge, SchemaViewerFlowNode } from "../../types";+import { getEdgeId, getFieldHandleId, getNodeId } from "../../utils";++import S from "./SchemaViewerFieldRow.module.css";++function getFieldIcon(field: ErdField): IconName {+ return getColumnIcon(+ Lib.legacyColumnTypeInfo({+ base_type: field.base_type ?? undefined,+ effective_type: field.effective_type ?? undefined,+ semantic_type: field.semantic_type,+ }),+ );+}++type SchemaViewerFieldRowProps = {+ field: ErdField;+ /** Field participates as the source side of at least one edge. */+ isSource: boolean;+ /** Field participates as the target side of at least one non-self-ref edge. */+ isTarget: boolean;+ isSelfRefTarget: boolean;+ isSelectedInEdge?: boolean;+};++export function SchemaViewerFieldRow({+ field,+ isSource,+ isTarget,+ isSelfRefTarget,+ isSelectedInEdge,+}: SchemaViewerFieldRowProps) {+ const { visibleTableIds, expandingTableIds, expandToTable, zoomToNode } =+ useSchemaViewerContext();+ const { setEdges } = useReactFlow<+ SchemaViewerFlowNode,+ SchemaViewerFlowEdge+ >();++ const isFkField = Lib.isForeignKey(Lib.legacyColumnTypeInfo(field));++ const icon: IconName = getFieldIcon(field);++ // FK field that has a target table not yet on the canvas+ const canExpand =+ isFkField &&+ field.fk_target_table_id != null &&+ !visibleTableIds.has(field.fk_target_table_id);++ // FK field that has a target table already on the canvas+ const canZoomTo =+ isFkField &&+ field.fk_target_table_id != null &&+ visibleTableIds.has(field.fk_target_table_id);++ // True while an FK-click fetch is in flight for this field's target table.+ const isExpanding =+ isFkField &&+ field.fk_target_table_id != null &&+ expandingTableIds.has(field.fk_target_table_id);++ const handleClick = (event: React.MouseEvent) => {+ // Keep the click from bubbling up to the node, otherwise React Flow+ // treats it as a node-click and clears all edge selection.+ event.stopPropagation();+ if (canExpand && field.fk_target_table_id != null) {+ // Pre-compute the edge IDs that will connect the FK field to its+ // target field after expansion to auto-highlight connecting edge. We pass both possible+ // orderings because the backend may put either field first in the+ // edge identifier.+ const candidateEdgeIds =+ field.fk_target_field_id != null+ ? [+ getEdgeId(field.id, field.fk_target_field_id),+ getEdgeId(field.fk_target_field_id, field.id),+ ]+ : undefined;+ expandToTable(field.fk_target_table_id, candidateEdgeIds);+ } else if (canZoomTo && field.fk_target_table_id != null) {+ const targetNodeId = getNodeId({+ table_id: field.fk_target_table_id,+ });+ zoomToNode(targetNodeId);++ // Same edge highlighting logic here.+ if (field.fk_target_field_id != null) {+ const candidateEdgeIds = new Set([+ getEdgeId(field.id, field.fk_target_field_id),+ getEdgeId(field.fk_target_field_id, field.id),+ ]);+ setEdges((edges) =>+ edges.map((edge) => {+ const shouldSelect = candidateEdgeIds.has(edge.id);+ if (shouldSelect && !edge.selected) {+ return { ...edge, selected: true };+ }+ if (!shouldSelect && edge.selected) {+ return { ...edge, selected: false };+ }+ return edge;+ }),+ );+ }+ }+ };++ const isClickable = canExpand || canZoomTo;++ return (+ <Group+ className={S.row}+ gap="sm"+ wrap="nowrap"+ h={ROW_HEIGHT_PX}+ px="md"+ data-clickable={isClickable || undefined}+ onClick={isClickable ? handleClick : undefined}+ style={{ cursor: isClickable ? "pointer" : undefined }}+ >+ <FixedSizeIcon+ name={icon}+ size={16}+ c={isSelectedInEdge ? "brand" : undefined}+ className={isSelectedInEdge ? undefined : S.icon}+ style={{ flexShrink: 0 }}+ />+ <Box+ className={cx(S.name, { [S.clickableName]: isClickable })}+ fz="sm"+ fw={isSelectedInEdge ? "bold" : "normal"}+ c={isSelectedInEdge ? "brand" : undefined}+ >+ {field.name}+ </Box>+ {isExpanding ? (+ <Loader size="xs" data-testid="schema-viewer-field-row-loader" />+ ) : (+ <Box fz="sm" c="text-secondary" style={{ flexShrink: 0 }}>+ {field.database_type.toLowerCase()}+ </Box>+ )}+ {canExpand && !isExpanding && <Box className={S.expandIndicator} />}+ {/* Handles are invisible but required for React Flow to draw edges. */}+ {isSource && (+ <Handle+ type="source"+ position={Position.Right}+ id={getFieldHandleId(field.id)}+ className={S.handle}+ />+ )}+ {isTarget && (+ <Handle+ type="target"+ position={Position.Left}+ id={getFieldHandleId(field.id)}+ className={S.handle}+ />+ )}+ {isSelfRefTarget && (+ <Handle+ type="target"+ position={Position.Right}+ id={getFieldHandleId(field.id, "right")}+ className={S.handle}+ />+ )}+ </Group>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerFieldRow.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerFieldRow.unit.spec.tsxnew file mode 100644index 00000000000..481966d03c7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerFieldRow.unit.spec.tsx@@ -0,0 +1,212 @@+import userEvent from "@testing-library/user-event";+import { ReactFlowProvider } from "@xyflow/react";++import { getIcon, renderWithProviders, screen } from "__support__/ui";+import type { ConcreteTableId, ErdField } from "metabase-types/api";++import { SchemaViewerContext } from "../../SchemaViewerContext";++import { SchemaViewerFieldRow } from "./SchemaViewerFieldRow";++type ContextOverrides = {+ visibleTableIds?: Set<ConcreteTableId>;+ expandingTableIds?: Set<ConcreteTableId>;+};++type SetupOpts = {+ field?: Partial<ErdField>;+ isSource?: boolean;+ isTarget?: boolean;+ isSelfRefTarget?: boolean;+ isSelectedInEdge?: boolean;+ context?: ContextOverrides;+};++function setup({+ field: fieldOverrides = {},+ isSource = false,+ isTarget = false,+ isSelfRefTarget = false,+ isSelectedInEdge = false,+ context: contextOverrides = {},+}: SetupOpts = {}) {+ const expandToTable = jest.fn();+ const zoomToNode = jest.fn();+ const selectNode = jest.fn();++ const field: ErdField = {+ id: 10,+ name: "user_id",+ display_name: "User ID",+ database_type: "integer",+ base_type: "type/Integer",+ effective_type: "type/Integer",+ semantic_type: null,+ fk_target_field_id: null,+ fk_target_table_id: null,+ ...fieldOverrides,+ };++ const value = {+ visibleTableIds:+ contextOverrides.visibleTableIds ?? new Set<ConcreteTableId>(),+ expandingTableIds:+ contextOverrides.expandingTableIds ?? new Set<ConcreteTableId>(),+ expandToTable,+ selectedNodeId: null,+ selectNode,+ zoomToNode,+ };++ renderWithProviders(+ <ReactFlowProvider>+ <SchemaViewerContext.Provider value={value}>+ <SchemaViewerFieldRow+ field={field}+ isSource={isSource}+ isTarget={isTarget}+ isSelfRefTarget={isSelfRefTarget}+ isSelectedInEdge={isSelectedInEdge}+ />+ </SchemaViewerContext.Provider>+ </ReactFlowProvider>,+ );++ return { expandToTable, zoomToNode };+}++describe("SchemaViewerFieldRow", () => {+ describe("icon mapping", () => {+ it("uses the `label` icon for primary keys", () => {+ setup({ field: { semantic_type: "type/PK" } });+ expect(getIcon("label")).toBeInTheDocument();+ });++ it("uses the `connections` icon for foreign keys", () => {+ setup({ field: { semantic_type: "type/FK", fk_target_table_id: 99 } });+ expect(getIcon("connections")).toBeInTheDocument();+ });++ it.each<[string, string]>([+ ["type/Boolean", "io"],+ ["type/DateTime", "calendar"],+ ["type/Date", "calendar"],+ ["type/Time", "calendar"],+ ["type/Integer", "int"],+ ["type/BigInteger", "int"],+ ["type/Float", "int"],+ ["type/Decimal", "int"],+ ["type/Text", "string"],+ ])("maps base_type=%s to the `%s` icon", (baseType, icon) => {+ setup({ field: { base_type: baseType, effective_type: baseType } });+ expect(getIcon(icon)).toBeInTheDocument();+ });++ it("falls back to the `list` icon for unrecognized types", () => {+ setup({+ field: {+ base_type: "type/Structured",+ effective_type: "type/Structured",+ },+ });+ expect(getIcon("list")).toBeInTheDocument();+ });+ });++ describe("click behavior", () => {+ it("clicking a plain non-FK field does not fire any handler", async () => {+ const { expandToTable, zoomToNode } = setup({+ field: { semantic_type: null },+ });+ await userEvent.click(screen.getByText("user_id"));+ expect(expandToTable).not.toHaveBeenCalled();+ expect(zoomToNode).not.toHaveBeenCalled();+ });++ it("clicking an FK field with a null target (permission-filtered) does not fire any handler", async () => {+ const { expandToTable, zoomToNode } = setup({+ field: {+ semantic_type: "type/FK",+ fk_target_table_id: null,+ fk_target_field_id: null,+ },+ });+ await userEvent.click(screen.getByText("user_id"));+ expect(expandToTable).not.toHaveBeenCalled();+ expect(zoomToNode).not.toHaveBeenCalled();+ });++ it("clicking an FK field whose target is off canvas calls onExpandToTable with both candidate edge ID orderings", async () => {+ const { expandToTable } = setup({+ field: {+ id: 10,+ semantic_type: "type/FK",+ fk_target_table_id: 99,+ fk_target_field_id: 999,+ },+ context: {+ visibleTableIds: new Set<ConcreteTableId>(),+ },+ });+ await userEvent.click(screen.getByText("user_id"));+ expect(expandToTable).toHaveBeenCalledWith(99, [+ "edge-10-999",+ "edge-999-10",+ ]);+ });++ it("clicking an FK field whose target is on canvas calls zoomToNode with `table-{targetId}`", async () => {+ const { zoomToNode } = setup({+ field: {+ id: 10,+ semantic_type: "type/FK",+ fk_target_table_id: 99,+ fk_target_field_id: 999,+ },+ context: {+ visibleTableIds: new Set([99]),+ },+ });+ await userEvent.click(screen.getByText("user_id"));+ expect(zoomToNode).toHaveBeenCalledWith("table-99");+ });+ });++ describe("expand-in-flight loader", () => {+ it("renders a Loader instead of the db type when target is in expandingTableIds", () => {+ setup({+ field: {+ semantic_type: "type/FK",+ fk_target_table_id: 99,+ fk_target_field_id: 999,+ database_type: "integer",+ },+ context: {+ expandingTableIds: new Set([99]),+ },+ });+ expect(screen.queryByText("integer")).not.toBeInTheDocument();+ expect(+ screen.getByTestId("schema-viewer-field-row-loader"),+ ).toBeInTheDocument();+ });++ it("does not render the loader when target is not in expandingTableIds", () => {+ setup({+ field: {+ semantic_type: "type/FK",+ fk_target_table_id: 99,+ fk_target_field_id: 999,+ database_type: "integer",+ },+ context: {+ expandingTableIds: new Set<ConcreteTableId>(),+ },+ });+ expect(screen.getByText("integer")).toBeInTheDocument();+ expect(+ screen.queryByTestId("schema-viewer-field-row-loader"),+ ).not.toBeInTheDocument();+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerTableNode.module.css b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerTableNode.module.cssnew file mode 100644index 00000000000..86bccf4f5bb--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerTableNode.module.css@@ -0,0 +1,22 @@+.card {+ --node-border-color: var(--mb-color-border);++ position: relative;+ width: 20rem;+ border: 1px solid var(--node-border-color);+ border-radius: 0.5rem;+ background: var(--mb-color-white);+ box-shadow: 0 0.25rem 1.25rem 0 rgba(0, 0, 0, 0.05);+}++.card.selected {+ --node-border-color: var(--mb-color-brand);+}++.header {+ border-bottom: 1px solid var(--mb-color-border);+}++.fields {+ overflow: visible;+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerTableNode.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerTableNode.tsxnew file mode 100644index 00000000000..1c7b786f51f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/SchemaViewerTableNode.tsx@@ -0,0 +1,84 @@+import type { NodeProps } from "@xyflow/react";+import cx from "classnames";+import { memo, useCallback } from "react";++import { Box, FixedSizeIcon, Group, Stack } from "metabase/ui";++import { useSchemaViewerContext } from "../../SchemaViewerContext";+import type { SchemaViewerFlowNode } from "../../types";++import { SchemaViewerFieldRow } from "./SchemaViewerFieldRow";+import S from "./SchemaViewerTableNode.module.css";++type SchemaViewerTableNodeProps = NodeProps<SchemaViewerFlowNode>;++export const SchemaViewerTableNode = memo(function SchemaViewerTableNode({+ id,+ data,+}: SchemaViewerTableNodeProps) {+ const { selectedNodeId, selectNode, zoomToNode } = useSchemaViewerContext();+ // Any field on this node sitting at either end of the currently selected+ // edge implies the node itself is connected to that edge.+ const isConnectedToSelectedEdge = data.selectedFieldIds.size > 0;+ const isUserSelected = selectedNodeId === id;++ const handleDoubleClick = useCallback(() => {+ zoomToNode(id);+ }, [id, zoomToNode]);++ const handleHeaderClick = useCallback(+ (event: React.MouseEvent) => {+ event.stopPropagation();+ selectNode(id);+ },+ [id, selectNode],+ );++ return (+ <Stack+ className={cx(S.card, {+ [S.selected]: isConnectedToSelectedEdge || isUserSelected,+ })}+ gap={0}+ onDoubleClick={handleDoubleClick}+ >+ <Group+ className={S.header}+ gap="sm"+ px="md"+ py="md"+ wrap="nowrap"+ onClick={handleHeaderClick}+ style={{ cursor: "pointer" }}+ >+ <FixedSizeIcon name="table" c="text-secondary" />+ <Box+ fz={17}+ lh="1.5rem"+ fw={700}+ c="text-primary"+ style={{+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ flex: 1,+ }}+ >+ {data.name}+ </Box>+ </Group>+ <Box className={S.fields}>+ {data.fields.map((field) => (+ <SchemaViewerFieldRow+ key={field.id}+ field={field}+ isSource={data.sourceFieldIds.has(field.id)}+ isTarget={data.targetFieldIds.has(field.id)}+ isSelfRefTarget={data.selfRefTargetFieldIds.has(field.id)}+ isSelectedInEdge={data.selectedFieldIds.has(field.id)}+ />+ ))}+ </Box>+ </Stack>+ );+});diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/index.tsnew file mode 100644index 00000000000..a4995783ae9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/TableNode/index.ts@@ -0,0 +1,2 @@+export { SchemaViewerTableNode } from "./SchemaViewerTableNode";+export { SchemaViewerFieldRow } from "./SchemaViewerFieldRow";diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/constants.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/constants.tsnew file mode 100644index 00000000000..c9f7ba7ff29--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/constants.ts@@ -0,0 +1,12 @@+export const ROW_HEIGHT_PX = 48;+export const HEADER_HEIGHT_PX = 56;+export const NODE_WIDTH_PX = 320;++const DEFAULT_ZOOM = 0.3;+// (if this value changes, update the same constant in e2e/test/scenarios/schema-viewer/schema-viewer.cy.spec.ts)+export const MIN_ZOOM = 0.3;+export const MAX_ZOOM = 1;+export const FIT_VIEW_OPTIONS = {+ minZoom: DEFAULT_ZOOM,+ maxZoom: DEFAULT_ZOOM,+};diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useCanvasLayout.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useCanvasLayout.tsnew file mode 100644index 00000000000..16e2a7d8d7c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useCanvasLayout.ts@@ -0,0 +1,60 @@+import { useCallback } from "react";++import type { SchemaViewerFlowEdge, SchemaViewerFlowNode } from "../types";+import { applyLayout } from "../utils/layout";++type UseCanvasLayoutArgs = {+ nodes: SchemaViewerFlowNode[];+ edges: SchemaViewerFlowEdge[];+ setNodes: React.Dispatch<React.SetStateAction<SchemaViewerFlowNode[]>>;+ setEdges: React.Dispatch<React.SetStateAction<SchemaViewerFlowEdge[]>>;+ zoomToNode: (nodeId: string) => void;+ zoomToCanvas: () => void;+};++type UseCanvasLayoutResult = {+ resetLayout: () => void;+ focusOnNode: (nodeId: string) => void;+};++/**+ * Manual layout actions exposed to the UI.+ */+export function useCanvasLayout({+ nodes,+ edges,+ setNodes,+ setEdges,+ zoomToNode,+ zoomToCanvas,+}: UseCanvasLayoutArgs): UseCanvasLayoutResult {+ const resetLayout = useCallback(() => {+ if (nodes.length === 0) {+ return;+ }+ const { nodes: laidOut } = applyLayout({ mode: "fresh", nodes, edges });+ setNodes(laidOut);+ zoomToCanvas();+ }, [nodes, edges, setNodes, zoomToCanvas]);++ const focusOnNode = useCallback(+ (nodeId: string) => {+ setNodes((currentNodes) => {+ const { nodes: laidOut } = applyLayout({+ mode: "focus",+ focalId: nodeId,+ nodes: currentNodes,+ edges,+ });+ return laidOut.map((n) => (n.selected ? { ...n, selected: false } : n));+ });+ setEdges((currentEdges) =>+ currentEdges.map((e) => (e.selected ? { ...e, selected: false } : e)),+ );+ zoomToNode(nodeId);+ },+ [edges, setNodes, setEdges, zoomToNode],+ );++ return { resetLayout, focusOnNode };+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useEdgeHandlers.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useEdgeHandlers.tsnew file mode 100644index 00000000000..e00e2dc7dbb--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useEdgeHandlers.ts@@ -0,0 +1,106 @@+import type { Dispatch, SetStateAction } from "react";+import { useCallback, useRef } from "react";++import type { SchemaViewerFlowEdge, SchemaViewerFlowNode } from "../types";++const EMPTY_FIELD_IDS: Set<number> = new Set();++type UseEdgeHandlersArgs = {+ zoomToNode: (nodeId: string) => void;+ setNodes: Dispatch<SetStateAction<SchemaViewerFlowNode[]>>;+ setEdges: Dispatch<SetStateAction<SchemaViewerFlowEdge[]>>;+};++export function useEdgeHandlers({+ zoomToNode,+ setNodes,+ setEdges,+}: UseEdgeHandlersArgs) {+ const lastEdgeSideRef = useRef<Map<string, "source" | "target">>(new Map());++ // Store information on current selected field ids on each node to avoid extracting it+ // from React Flow store through `useStore()` which is much more expensive (fires on every canvas interaction).+ const setSelectedFieldIds = useCallback(+ (globalIds: Set<number>) => {+ setNodes((prev) =>+ prev.map((node) => {+ const next = new Set<number>();+ if (globalIds.size > 0) {+ for (const f of node.data.fields) {+ if (globalIds.has(f.id)) {+ next.add(f.id);+ }+ }+ }+ const existing = node.data.selectedFieldIds;+ if (next.size === 0 && existing.size === 0) {+ return node;+ }+ if (next.size === existing.size) {+ let same = true;+ for (const id of next) {+ if (!existing.has(id)) {+ same = false;+ break;+ }+ }+ if (same) {+ return node;+ }+ }+ return {+ ...node,+ data: { ...node.data, selectedFieldIds: next },+ };+ }),+ );+ },+ [setNodes],+ );++ const handleEdgeClick = useCallback(+ (_event: React.MouseEvent, edge: SchemaViewerFlowEdge) => {+ setSelectedFieldIds(getEdgeFieldIds(edge));++ if (!edge.selected) {+ return;+ }+ const previousSide = lastEdgeSideRef.current.get(edge.id);+ const nextSide: "source" | "target" =+ previousSide === "source" ? "target" : "source";+ lastEdgeSideRef.current.set(edge.id, nextSide);+ const targetNodeId = nextSide === "source" ? edge.source : edge.target;+ zoomToNode(targetNodeId);+ },+ [zoomToNode, setSelectedFieldIds],+ );++ const clearEdgeSelection = useCallback(() => {+ setEdges((currentEdges) =>+ currentEdges.map((e) => (e.selected ? { ...e, selected: false } : e)),+ );+ setSelectedFieldIds(EMPTY_FIELD_IDS);+ }, [setEdges, setSelectedFieldIds]);++ return { handleEdgeClick, clearEdgeSelection };+}++function getEdgeFieldIds(edge: SchemaViewerFlowEdge): Set<number> {+ const ids = new Set<number>();+ addFieldIdFromHandle(ids, edge.sourceHandle);+ addFieldIdFromHandle(ids, edge.targetHandle);+ return ids;+}++function addFieldIdFromHandle(+ ids: Set<number>,+ handle: string | null | undefined,+) {+ if (handle == null) {+ return;+ }+ const match = /^field-(\d+)/.exec(handle);+ if (match) {+ ids.add(Number(match[1]));+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useGraphSync.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useGraphSync.tsnew file mode 100644index 00000000000..d7315f78b14--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useGraphSync.ts@@ -0,0 +1,246 @@+import {+ type Dispatch,+ type SetStateAction,+ useCallback,+ useEffect,+ useRef,+} from "react";+import { useLatest } from "react-use";++import type {+ ConcreteTableId,+ DatabaseId,+ SchemaName,+} from "metabase-types/api";++import type { SchemaViewerFlowEdge, SchemaViewerFlowNode } from "../types";+import { applyLayout, getNodeId } from "../utils";++type UseGraphSyncArgs = {+ hasDbSelected: boolean;+ error: unknown;+ isFetching: boolean;+ // Normalized /erd response.+ graph: {+ nodes: SchemaViewerFlowNode[];+ edges: SchemaViewerFlowEdge[];+ } | null;+ // Nodes from useNodesState (already positioned on the canvas) — needed for incremental position merge.+ nodes: SchemaViewerFlowNode[];+ contextKey: `${DatabaseId}__${SchemaName}` | null;+ setNodes: (nodes: SchemaViewerFlowNode[]) => void;+ setEdges: (edges: SchemaViewerFlowEdge[]) => void;+ setExpandingTableIds: Dispatch<SetStateAction<Set<ConcreteTableId>>>;+ zoomToNode: (nodeId: string) => void;+ zoomToCanvas: () => void;+};++type PendingExpansion = {+ // Node ID of the table the user expanded into — zoom target.+ targetNodeId: string;+ // Edge IDs to auto-select when node is rendered.+ candidateEdgeIds: readonly string[];+};++const clearExpandingTableIds = (prev: Set<ConcreteTableId>) =>+ prev.size === 0 ? prev : new Set<ConcreteTableId>();++function markPendingEdgeSelected(+ edges: SchemaViewerFlowEdge[],+ pending: PendingExpansion | null,+) {+ if (pending == null || pending.candidateEdgeIds.length === 0) {+ return edges;+ }++ const matchedId = pending.candidateEdgeIds.find((candidate) =>+ edges.some((edge) => edge.id === candidate),+ );++ if (matchedId == null) {+ return edges;+ }++ return edges.map((edge) =>+ edge.id === matchedId ? { ...edge, selected: true } : edge,+ );+}++function getExpandingTableIds(+ currentExpandingTableIds: Set<ConcreteTableId>,+ visibleNodes: SchemaViewerFlowNode[],+) {+ if (currentExpandingTableIds.size === 0) {+ return currentExpandingTableIds;+ }++ const visibleIds = new Set(visibleNodes.map((node) => node.data.table_id));+ let hasChanges = false;+ const newExpandingTableIds = new Set<ConcreteTableId>();++ for (const id of currentExpandingTableIds) {+ if (visibleIds.has(id)) {+ hasChanges = true;+ } else {+ newExpandingTableIds.add(id);+ }+ }++ return hasChanges ? newExpandingTableIds : currentExpandingTableIds;+}++function getMergedGraphLayout({+ graph,+ currentNodes,+}: {+ graph: NonNullable<UseGraphSyncArgs["graph"]>;+ currentNodes: SchemaViewerFlowNode[];+}) {+ return applyLayout({+ mode: "merge",+ incoming: graph.nodes,+ current: currentNodes,+ edges: graph.edges,+ });+}++function focusSyncedGraph({+ layout,+ pendingExpansionRef,+ zoomToNode,+ zoomToCanvas,+}: {+ layout: ReturnType<typeof applyLayout>;+ pendingExpansionRef: { current: PendingExpansion | null };+ zoomToNode: (nodeId: string) => void;+ zoomToCanvas: () => void;+}) {+ const pending = pendingExpansionRef.current;++ if (layout.preservedExistingPositions) {+ // Incremental add: zoom onto the user-requested target if it's now in+ // the graph.+ if (+ pending != null &&+ layout.nodes.some((node) => node.id === pending.targetNodeId)+ ) {+ zoomToNode(pending.targetNodeId);+ pendingExpansionRef.current = null;+ }+ } else {+ // Fresh layout: fit the whole canvas.+ zoomToCanvas();+ pendingExpansionRef.current = null;+ }+}++/**+ * Owns the data → React Flow state sync for the schema viewer:+ *+ * - Clears the canvas immediately on context change (database/schema swap).+ * - When ERD response arrives: either lays out a fresh canvas or merges incoming nodes with the+ * current canvas to preserve positions of tables that were already+ * placed.+ * - On FK expansion: once the new graph arrives, auto-selects the FK edge+ * that triggered the expansion AND zooms onto the new target table.+ */+export function useGraphSync({+ hasDbSelected,+ error,+ isFetching,+ graph,+ nodes,+ contextKey,+ setNodes,+ setEdges,+ setExpandingTableIds,+ zoomToNode,+ zoomToCanvas,+}: UseGraphSyncArgs) {+ /**+ * Register the FK-expansion target. Once the next ERD response includes+ * a node for `targetTableId`, graph sync auto-selects the connecting+ * edge (from `candidateEdgeIds`) and zooms onto that node.+ *+ * `candidateEdgeIds` should include both source-first and target-first+ * orderings since the backend's source/target convention isn't fixed.+ */+ const pendingExpansionRef = useRef<PendingExpansion | null>(null);+ const registerPendingExpansion = useCallback(+ (targetTableId: ConcreteTableId, candidateEdgeIds?: readonly string[]) => {+ pendingExpansionRef.current = {+ targetNodeId: getNodeId({ table_id: targetTableId }),+ candidateEdgeIds: candidateEdgeIds ?? [],+ };+ },+ [],+ );++ const nodesRef = useLatest(nodes);+ const shouldClearCanvas = !hasDbSelected || error != null;+ const renderedGraph = shouldClearCanvas || isFetching ? null : graph;++ // Clear the canvas whenever the database/schema context changes.+ const prevContextForClearRef = useRef(contextKey);+ if (prevContextForClearRef.current !== contextKey) {+ prevContextForClearRef.current = contextKey;+ setNodes([]);+ setEdges([]);+ setExpandingTableIds(clearExpandingTableIds);+ pendingExpansionRef.current = null;+ }++ useEffect(() => {+ if (shouldClearCanvas) {+ setNodes([]);+ setEdges([]);+ setExpandingTableIds(clearExpandingTableIds);+ pendingExpansionRef.current = null;+ }+ }, [shouldClearCanvas, setEdges, setExpandingTableIds, setNodes]);++ useEffect(() => {+ if (renderedGraph == null) {+ return;+ }++ // If we expanded via FK click and a matching edge has now arrived in+ // the new graph, mark it as selected.+ setEdges(+ markPendingEdgeSelected(renderedGraph.edges, pendingExpansionRef.current),+ );+ }, [renderedGraph, setEdges]);++ useEffect(() => {+ if (renderedGraph == null) {+ return;+ }++ const layout = getMergedGraphLayout({+ graph: renderedGraph,+ currentNodes: nodesRef.current,+ });++ setNodes(layout.nodes);+ focusSyncedGraph({+ layout,+ pendingExpansionRef,+ zoomToNode,+ zoomToCanvas,+ });+ }, [nodesRef, renderedGraph, setNodes, zoomToCanvas, zoomToNode]);++ useEffect(() => {+ if (renderedGraph == null) {+ return;+ }++ // Clear any expand-in-flight markers for tables that just arrived in the+ // new graph (or that are no longer in the selection).+ setExpandingTableIds((prev) =>+ getExpandingTableIds(prev, renderedGraph.nodes),+ );+ }, [renderedGraph, setExpandingTableIds]);++ return { registerPendingExpansion };+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useSchemaPreferencesStore.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useSchemaPreferencesStore.tsnew file mode 100644index 00000000000..5f241dda88e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useSchemaPreferencesStore.ts@@ -0,0 +1,141 @@+import { useCallback, useState } from "react";+import { usePrevious } from "react-use";++import { useUserKeyValue } from "metabase/common/hooks/use-user-key-value";+import type {+ ConcreteTableId,+ DatabaseId,+ SchemaName,+} from "metabase-types/api";++type UseSchemaPreferencesStoreArgs = {+ databaseId: DatabaseId | undefined;+ schema: string | undefined;+ initialTableIds: ConcreteTableId[] | undefined;+};++type UseSchemaPreferencesStoreResult = {+ /**+ * External table IDs for the current context — specifically+ * tables from OTHER schemas that the user expanded into via FK click.+ * When a `schema` is set the backend returns all tables in that schema+ * automatically, so we never put schema-native tables in this set.+ */+ extraTableIds: readonly ConcreteTableId[];+ addExtraTableId: (tableId: ConcreteTableId) => void;+ contextKey: `${DatabaseId}__${SchemaName}` | null;+ isRestoring: boolean;+};++const EMPTY_IDS: readonly ConcreteTableId[] = [];++/**+ * Owns per-context `schema_viewer` UserKeyValue restoration:+ *+ * - `${databaseId}__${schema}` key: persisted set of "extra"+ * table IDs. Restored on first visit to a context; written on each FK+ * expansion.+ *+ * Initialization rules per context for the extra-tables set:+ * 1. If the URL provided initialTableIds (non-empty), seed from URL and+ * consider this context initialized — saved prefs are ignored.+ * 2. Otherwise wait for saved prefs to arrive and seed from them.+ */+export function useSchemaPreferencesStore({+ databaseId,+ schema,+ initialTableIds,+}: UseSchemaPreferencesStoreArgs): UseSchemaPreferencesStoreResult {+ const contextKey: `${DatabaseId}__${SchemaName}` | null =+ databaseId != null ? `${databaseId}__${schema ?? ""}` : null;++ const {+ // Use `currentValue` (RTK Query's `currentData`) rather than `value` so+ // synchronous restoration on context switch is not poisoned by the+ // previous context's value. `value` is sticky across arg changes;+ // `currentValue` is `undefined` until the new subscription resolves.+ currentValue: savedPrefs,+ setValue: setSavedPrefs,+ isLoading: isLoadingSavedPrefs,+ } = useUserKeyValue({+ namespace: "schema_viewer",+ key: contextKey ?? "",+ skip: contextKey == null,+ });++ const [tableIdsByContext, setTableIdsByContext] = useState<+ ReadonlyMap<string, readonly ConcreteTableId[]>+ >(() => {+ const map = new Map<string, readonly ConcreteTableId[]>();+ if (+ contextKey != null &&+ initialTableIds != null &&+ initialTableIds.length > 0+ ) {+ map.set(contextKey, initialTableIds);+ }+ return map;+ });++ const prevContextKey = usePrevious(contextKey);+ if (prevContextKey !== contextKey) {+ if (+ contextKey != null &&+ initialTableIds != null &&+ initialTableIds.length > 0 &&+ !tableIdsByContext.has(contextKey)+ ) {+ setTableIdsByContext((prev) => {+ const next = new Map(prev);+ next.set(contextKey, initialTableIds);+ return next;+ });+ }+ }++ const isRestoring = contextKey != null && !tableIdsByContext.has(contextKey);++ if (+ isRestoring &&+ contextKey != null &&+ !isLoadingSavedPrefs &&+ savedPrefs !== undefined+ ) {+ const restoredIds = savedPrefs != null ? savedPrefs.table_ids : EMPTY_IDS;+ setTableIdsByContext((prev) => {+ if (prev.has(contextKey)) {+ return prev;+ }+ const next = new Map(prev);+ next.set(contextKey, restoredIds);+ return next;+ });+ }++ const extraTableIds =+ contextKey != null+ ? (tableIdsByContext.get(contextKey) ?? EMPTY_IDS)+ : EMPTY_IDS;++ const addExtraTableId = useCallback(+ (tableId: ConcreteTableId) => {+ if (contextKey == null) {+ return;+ }+ setTableIdsByContext((prev) => {+ const current = prev.get(contextKey) ?? EMPTY_IDS;+ if (current.includes(tableId)) {+ return prev;+ }+ const next = [...current, tableId];+ setSavedPrefs({ table_ids: next });+ const newMap = new Map(prev);+ newMap.set(contextKey, next);+ return newMap;+ });+ },+ [contextKey, setSavedPrefs],+ );++ return { extraTableIds, addExtraTableId, contextKey, isRestoring };+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useSchemaViewerZoomMethods.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useSchemaViewerZoomMethods.tsnew file mode 100644index 00000000000..e932d247ba2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/hooks/useSchemaViewerZoomMethods.ts@@ -0,0 +1,115 @@+import type { ReactFlowInstance } from "@xyflow/react";+import { useCallback, useEffect, useRef } from "react";++import type { SchemaViewerFlowEdge, SchemaViewerFlowNode } from "../types";+import {+ ZOOM_DURATION_MS,+ zoomToNode as zoomToNodeInternal,+} from "../utils/zoom";++type PendingZoomRequest =+ | { kind: "all" }+ | { kind: "node"; nodeId: string; retriesLeft: number };++// When `setNodes` and `zoomToNode` fire in the same useEffect, the ReactFlow+// store may not yet have the new node by the time the first rAF fires.+// We retry across a few frames so the zoom lands once the store has caught up.+const NODE_ZOOM_MAX_RETRIES = 8;++type SchemaViewerInstance = ReactFlowInstance<+ SchemaViewerFlowNode,+ SchemaViewerFlowEdge+>;++export type SchemaViewerZoomMethods = {+ zoomToNode: (nodeId: string) => void;+ zoomToCanvas: () => void;+ cancelZoom: () => void;+};++export function useSchemaViewerZoomMethods(+ instance: SchemaViewerInstance | null,+): SchemaViewerZoomMethods {+ const instanceRef = useRef(instance);+ instanceRef.current = instance;++ const pendingZoomRequestRef = useRef<PendingZoomRequest | null>(null);+ const nextTickRef = useRef<number | null>(null);++ // `schedule` and `drain` reference each other — declare `schedule` via ref+ // so `drain` can re-arm the next tick for retry without a dependency cycle.+ const scheduleRef = useRef<() => void>(() => {});++ const drain = useCallback(() => {+ nextTickRef.current = null;+ const pendingZoomRequest = pendingZoomRequestRef.current;+ const instance = instanceRef.current;+ if (pendingZoomRequest == null || instance == null) {+ pendingZoomRequestRef.current = null;+ return;+ }+ if (pendingZoomRequest.kind === "all") {+ pendingZoomRequestRef.current = null;+ instance.fitView({ duration: ZOOM_DURATION_MS });+ return;+ }+ const succeeded = zoomToNodeInternal(instance, pendingZoomRequest.nodeId);+ if (succeeded) {+ pendingZoomRequestRef.current = null;+ return;+ }+ // Target node not yet in the ReactFlow store — try again next frame+ // so the camera still lands on it once the store sync catches up.+ if (pendingZoomRequest.retriesLeft > 0) {+ pendingZoomRequestRef.current = {+ ...pendingZoomRequest,+ retriesLeft: pendingZoomRequest.retriesLeft - 1,+ };+ scheduleRef.current();+ return;+ }+ pendingZoomRequestRef.current = null;+ }, []);++ const scheduleZoom = useCallback(() => {+ if (nextTickRef.current != null) {+ return;+ }+ nextTickRef.current = requestAnimationFrame(drain);+ }, [drain]);++ scheduleRef.current = scheduleZoom;++ useEffect(() => {+ if (instance != null && pendingZoomRequestRef.current != null) {+ scheduleZoom();+ }+ }, [instance, scheduleZoom]);++ const zoomToNode = useCallback(+ (nodeId: string) => {+ pendingZoomRequestRef.current = {+ kind: "node",+ nodeId,+ retriesLeft: NODE_ZOOM_MAX_RETRIES,+ };+ scheduleZoom();+ },+ [scheduleZoom],+ );++ const zoomToCanvas = useCallback(() => {+ pendingZoomRequestRef.current = { kind: "all" };+ scheduleZoom();+ }, [scheduleZoom]);++ const cancelZoom = useCallback(() => {+ pendingZoomRequestRef.current = null;+ if (nextTickRef.current != null) {+ cancelAnimationFrame(nextTickRef.current);+ nextTickRef.current = null;+ }+ }, []);++ return { zoomToNode, zoomToCanvas, cancelZoom };+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/index.tsnew file mode 100644index 00000000000..71372eb4c8a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/index.ts@@ -0,0 +1 @@+export { SchemaViewer } from "./SchemaViewer";diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/types.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/types.tsnew file mode 100644index 00000000000..baaf5e61b8c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/types.ts@@ -0,0 +1,23 @@+import type { Edge, Node } from "@xyflow/react";++import type { ErdNode, ErdRelationship, FieldId } from "metabase-types/api";++export type SchemaViewerNodeData = ErdNode & {+ // Fields that act as the source side of some edge on this table.+ sourceFieldIds: Set<FieldId>;+ // Fields that act as the target side of a non-self-referential edge.+ targetFieldIds: Set<FieldId>;+ // Fields that act as the target side of a self-referential edge — they+ // render an extra handle on the right, since the matching source handle+ // also sits on the right of the same node.+ selfRefTargetFieldIds: Set<FieldId>;+ // Fields on this table that sit at either end of the currently selected+ // edge. Pre-computed at edge-click.+ selectedFieldIds: Set<FieldId>;+};+export type SchemaViewerFlowNode = Node<SchemaViewerNodeData>;++export type SchemaViewerEdgeData = {+ relationship: ErdRelationship;+};+export type SchemaViewerFlowEdge = Edge<SchemaViewerEdgeData>;diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/flow-graph.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/flow-graph.tsnew file mode 100644index 00000000000..b4335b0860b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/flow-graph.ts@@ -0,0 +1,200 @@+import { memoize } from "underscore";++import * as Lib from "metabase-lib";+import type {+ ErdEdge,+ ErdField,+ ErdNode,+ ErdResponse,+ FieldId,+ TableId,+} from "metabase-types/api";++import { HEADER_HEIGHT_PX, NODE_WIDTH_PX, ROW_HEIGHT_PX } from "../constants";+import type { SchemaViewerFlowEdge, SchemaViewerFlowNode } from "../types";++export function getNodeId(node: { table_id: TableId } | TableId): string {+ const tableId = typeof node === "object" ? node.table_id : node;+ return `table-${tableId}`;+}++export function getEdgeId(+ sourceFieldId: FieldId,+ targetFieldId: FieldId,+): string {+ return `edge-${sourceFieldId}-${targetFieldId}`;+}++// `side` distinguishes the right-side * handle used to anchor self-referential edges.+export function getFieldHandleId(fieldId: FieldId, side?: "right"): string {+ return side ? `field-${fieldId}-${side}` : `field-${fieldId}`;+}++export function getNodeHeight(fieldCount: number): number {+ return HEADER_HEIGHT_PX + fieldCount * ROW_HEIGHT_PX;+}++// Sort fields so PKs come first, then FKs, then the rest+function sortFields(fields: ErdField[]): ErdField[] {+ return [...fields].sort((a, b) => {+ const aPK = Lib.isPrimaryKey(Lib.legacyColumnTypeInfo(a));+ const bPK = Lib.isPrimaryKey(Lib.legacyColumnTypeInfo(b));+ const aFK = Lib.isForeignKey(Lib.legacyColumnTypeInfo(a));+ const bFK = Lib.isForeignKey(Lib.legacyColumnTypeInfo(b));++ if (aPK && !bPK) {+ return -1;+ }+ if (!aPK && bPK) {+ return 1;+ }+ if (aFK && !bFK) {+ return -1;+ }+ if (!aFK && bFK) {+ return 1;+ }++ return 0;+ });+}++type TableEdgeRoles = {+ sourceFieldIds: Set<number>;+ targetFieldIds: Set<number>;+ selfRefTargetFieldIds: Set<number>;+};++const EMPTY_ROLES: TableEdgeRoles = {+ sourceFieldIds: new Set(),+ targetFieldIds: new Set(),+ selfRefTargetFieldIds: new Set(),+};++// Nodes should sit above all edges and have higher z-index, but it should be provided+// here (not from CSS), because otherwise React Flow inlines it with "0" value (even when+// set to `null`).+const NODE_Z_INDEX = 2;++function toFlowNode(+ node: ErdNode,+ roles: TableEdgeRoles,+): SchemaViewerFlowNode {+ return {+ id: getNodeId(node),+ type: "schemaViewerTable",+ position: { x: 0, y: 0 },+ zIndex: NODE_Z_INDEX,+ data: {+ ...node,+ fields: sortFields(node.fields),+ sourceFieldIds: roles.sourceFieldIds,+ targetFieldIds: roles.targetFieldIds,+ selfRefTargetFieldIds: roles.selfRefTargetFieldIds,+ selectedFieldIds: new Set(),+ },+ style: {+ width: NODE_WIDTH_PX,+ height: getNodeHeight(node.fields.length),+ opacity: 0, // Hide until positioned by dagre layout+ },+ };+}++function toFlowEdge(edge: ErdEdge): SchemaViewerFlowEdge {+ const isSelfRef = edge.source_table_id === edge.target_table_id;+ return {+ id: getEdgeId(edge.source_field_id, edge.target_field_id),+ source: getNodeId(edge.source_table_id),+ target: getNodeId(edge.target_table_id),+ sourceHandle: getFieldHandleId(edge.source_field_id),+ targetHandle: getFieldHandleId(+ edge.target_field_id,+ isSelfRef ? "right" : undefined,+ ),+ type: "schemaViewerEdge",+ // @ts-expect-error - without providing null here, ReactFlow inlines it as 0.+ zIndex: null,+ data: {+ relationship: edge.relationship,+ },+ };+}++function getFlowGraphMemoKey(data: ErdResponse): string {+ const nodeKey = data.nodes+ .map((node) => {+ const fieldKey = node.fields+ .map(+ (f) =>+ `${f.id}:${f.name}:${f.display_name}:${f.database_type}:${f.base_type}:${f.effective_type ?? ""}:${f.semantic_type ?? ""}:${f.fk_target_field_id ?? ""}:${f.fk_target_table_id ?? ""}`,+ )+ .join("|");+ return `${node.table_id}:${node.name}:${node.display_name}:${node.description ?? ""}:${getOwnerKey(node.owner)}:${node.schema ?? ""}:${fieldKey}`;+ })+ .sort()+ .join(";");++ const edgeKey = data.edges+ .map(+ (edge) =>+ `${edge.source_table_id}:${edge.source_field_id}->${edge.target_table_id}:${edge.target_field_id}:${edge.relationship}`,+ )+ .sort()+ .join(";");++ return `${nodeKey}__${edgeKey}`;+}++function getOwnerKey(owner: ErdNode["owner"]): string {+ if (owner == null) {+ return "";+ }+ if ("id" in owner && owner.id != null) {+ return `u_${owner.id}`;+ }+ return `e_${owner.email}`;+}++const memoizedToFlowGraph = memoize((data: ErdResponse) => {+ // Per-table field roles: which fields act as source, target, or self-ref target+ // of any edge. Handles rendering is based on this (not on semantic_type) so an+ // edge whose target field isn't tagged as a PK still gets a matching handle.+ const rolesByTable = new Map<TableId, TableEdgeRoles>();+ const ensureRoles = (tableId: TableId): TableEdgeRoles => {+ let roles = rolesByTable.get(tableId);+ if (roles == null) {+ roles = {+ sourceFieldIds: new Set(),+ targetFieldIds: new Set(),+ selfRefTargetFieldIds: new Set(),+ };+ rolesByTable.set(tableId, roles);+ }+ return roles;+ };+ for (const edge of data.edges) {+ ensureRoles(edge.source_table_id).sourceFieldIds.add(edge.source_field_id);+ const isSelfRef = edge.source_table_id === edge.target_table_id;+ const targetRoles = ensureRoles(edge.target_table_id);+ if (isSelfRef) {+ targetRoles.selfRefTargetFieldIds.add(edge.target_field_id);+ } else {+ targetRoles.targetFieldIds.add(edge.target_field_id);+ }+ }++ return {+ nodes: data.nodes.map((node) =>+ toFlowNode(node, rolesByTable.get(node.table_id) ?? EMPTY_ROLES),+ ),+ edges: data.edges.map((edge) => toFlowEdge(edge)),+ };+}, getFlowGraphMemoKey);++export function toFlowGraph(data: ErdResponse): {+ nodes: SchemaViewerFlowNode[];+ edges: SchemaViewerFlowEdge[];+} {+ return memoizedToFlowGraph(data);+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/flow-graph.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/flow-graph.unit.spec.tsnew file mode 100644index 00000000000..aedeafe0302--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/flow-graph.unit.spec.ts@@ -0,0 +1,205 @@+import type { ErdResponse } from "metabase-types/api";+import {+ createMockErdEdge,+ createMockErdField,+ createMockErdNode,+} from "metabase-types/api/mocks";++import { HEADER_HEIGHT_PX, ROW_HEIGHT_PX } from "../constants";++import { getNodeHeight, getNodeId, toFlowGraph } from "./flow-graph";++describe("getNodeId", () => {+ it("returns `table-${table_id}`", () => {+ expect(getNodeId({ table_id: 7 })).toBe("table-7");+ });+});++describe("getNodeHeight", () => {+ it("returns HEADER_HEIGHT + fieldCount * ROW_HEIGHT", () => {+ expect(getNodeHeight(0)).toBe(HEADER_HEIGHT_PX);+ expect(getNodeHeight(3)).toBe(HEADER_HEIGHT_PX + 3 * ROW_HEIGHT_PX);+ });+});++describe("toFlowGraph — field sort order", () => {+ it("places PK rows first, then FK rows, then everything else (preserving original order within categories)", () => {+ const response: ErdResponse = {+ nodes: [+ createMockErdNode({+ table_id: 1,+ fields: [+ createMockErdField({ id: 1, name: "extra_a", semantic_type: null }),+ createMockErdField({+ id: 2,+ name: "fk_b",+ semantic_type: "type/FK",+ }),+ createMockErdField({+ id: 3,+ name: "pk_c",+ semantic_type: "type/PK",+ }),+ createMockErdField({ id: 4, name: "extra_d", semantic_type: null }),+ createMockErdField({+ id: 5,+ name: "fk_e",+ semantic_type: "type/FK",+ }),+ createMockErdField({+ id: 6,+ name: "pk_f",+ semantic_type: "type/PK",+ }),+ ],+ }),+ ],+ edges: [],+ };++ const { nodes } = toFlowGraph(response);+ expect(nodes[0].data.fields.map((f) => f.name)).toEqual([+ "pk_c",+ "pk_f",+ "fk_b",+ "fk_e",+ "extra_a",+ "extra_d",+ ]);+ });+});++describe("toFlowGraph — edge ids and handles", () => {+ it("generates edge id from source and target field ids", () => {+ const response: ErdResponse = {+ nodes: [],+ edges: [createMockErdEdge({ source_field_id: 10, target_field_id: 20 })],+ };+ const { edges } = toFlowGraph(response);+ expect(edges[0].id).toBe("edge-10-20");+ });++ it("uses non-self-ref handles when source and target tables differ", () => {+ const response: ErdResponse = {+ nodes: [],+ edges: [createMockErdEdge({ source_table_id: 1, target_table_id: 2 })],+ };+ const { edges } = toFlowGraph(response);+ expect(edges[0].source).toBe("table-1");+ expect(edges[0].target).toBe("table-2");+ expect(edges[0].sourceHandle).toBe("field-10");+ expect(edges[0].targetHandle).toBe("field-20");+ });++ it("uses the right-side target handle for self-referential edges", () => {+ const response: ErdResponse = {+ nodes: [],+ edges: [+ createMockErdEdge({+ source_table_id: 1,+ target_table_id: 1,+ source_field_id: 10,+ target_field_id: 11,+ }),+ ],+ };+ const { edges } = toFlowGraph(response);+ expect(edges[0].source).toBe("table-1");+ expect(edges[0].target).toBe("table-1");+ expect(edges[0].targetHandle).toBe("field-11-right");+ });++ it("preserves the relationship value in the flow edge data", () => {+ const response: ErdResponse = {+ nodes: [],+ edges: [+ createMockErdEdge({+ relationship: "one-to-one",+ source_field_id: 1,+ target_field_id: 2,+ }),+ createMockErdEdge({+ relationship: "many-to-one",+ source_field_id: 3,+ target_field_id: 4,+ }),+ ],+ };+ const { edges } = toFlowGraph(response);+ expect(edges[0].data?.relationship).toBe("one-to-one");+ expect(edges[1].data?.relationship).toBe("many-to-one");+ });+});++describe("toFlowGraph — per-table edge roles", () => {+ it("populates sourceFieldIds, targetFieldIds, and selfRefTargetFieldIds correctly", () => {+ const response: ErdResponse = {+ nodes: [+ createMockErdNode({+ table_id: 1,+ fields: [createMockErdField({ id: 10 })],+ }),+ createMockErdNode({+ table_id: 2,+ fields: [createMockErdField({ id: 20 })],+ }),+ ],+ edges: [+ createMockErdEdge({+ source_table_id: 1,+ source_field_id: 10,+ target_table_id: 2,+ target_field_id: 20,+ }),+ createMockErdEdge({+ source_table_id: 2,+ source_field_id: 21,+ target_table_id: 2,+ target_field_id: 22,+ }),+ ],+ };+ const { nodes } = toFlowGraph(response);+ const t1 = nodes.find((n) => n.id === "table-1")!;+ const t2 = nodes.find((n) => n.id === "table-2")!;++ expect([...t1.data.sourceFieldIds]).toEqual([10]);+ expect([...t1.data.targetFieldIds]).toEqual([]);+ expect([...t1.data.selfRefTargetFieldIds]).toEqual([]);++ expect([...t2.data.sourceFieldIds]).toEqual([21]);+ expect([...t2.data.targetFieldIds]).toEqual([20]);+ expect([...t2.data.selfRefTargetFieldIds]).toEqual([22]);+ });+});++describe("toFlowGraph — memoization", () => {+ it("returns the same reference when called twice with deep-equal responses", () => {+ const responseA: ErdResponse = {+ nodes: [+ createMockErdNode({+ table_id: 1,+ fields: [createMockErdField({ id: 10 })],+ }),+ ],+ edges: [createMockErdEdge({ source_field_id: 10, target_field_id: 20 })],+ };+ const responseB: ErdResponse = JSON.parse(JSON.stringify(responseA));++ const a = toFlowGraph(responseA);+ const b = toFlowGraph(responseB);+ expect(a).toBe(b);+ });++ it("returns a different reference when an edge's relationship changes", () => {+ const responseA: ErdResponse = {+ nodes: [],+ edges: [createMockErdEdge({ relationship: "many-to-one" })],+ };+ const responseB: ErdResponse = {+ nodes: [],+ edges: [createMockErdEdge({ relationship: "one-to-one" })],+ };+ expect(toFlowGraph(responseA)).not.toBe(toFlowGraph(responseB));+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/index.tsnew file mode 100644index 00000000000..9b43f56e7e0--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/index.ts@@ -0,0 +1,7 @@+export {+ getEdgeId,+ getFieldHandleId,+ getNodeId,+ toFlowGraph,+} from "./flow-graph";+export { applyLayout } from "./layout";diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout.tsnew file mode 100644index 00000000000..26a6f938a3c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout.ts@@ -0,0 +1,78 @@+import type { SchemaViewerFlowNode } from "../types";++import { layoutWithDagre } from "./layout/dagre-layout";+import { focusNodeLayout } from "./layout/focal-layout";+import { mergeWithExistingPositions } from "./layout/incremental-layout";+import type { LayoutEdge } from "./layout/types";++export { DAGRE_NODE_SEP_PX, DAGRE_RANK_SEP_PX } from "./layout/constants";+export type { LayoutEdge } from "./layout/types";++/**+ * Layout request shape consumed by {@link applyLayout}. Three modes cover the+ * full set of canvas-layout actions in the schema viewer:+ *+ * - `fresh`: lay everything out from scratch via Dagre (manual auto-layout+ * button, or fallback when an incremental merge isn't possible).+ * - `focus`: rearrange around "focal table" — incoming relationships stack on the+ * left, outgoing on the right, the rest are placed further on the side using default algorithm.+ * - `merge`: try to preserve existing positions when the underlying graph+ * changes incrementally (e.g. FK click adds a new table).+ * */+export type LayoutRequest =+ | {+ mode: "fresh";+ nodes: SchemaViewerFlowNode[];+ edges: LayoutEdge[];+ }+ | {+ mode: "focus";+ focalId: string;+ nodes: SchemaViewerFlowNode[];+ edges: LayoutEdge[];+ }+ | {+ mode: "merge";+ incoming: SchemaViewerFlowNode[];+ current: SchemaViewerFlowNode[];+ edges: LayoutEdge[];+ };++export type LayoutResult = {+ nodes: SchemaViewerFlowNode[];+ // Indicate whether node positions were preserved during incremental merge.+ preservedExistingPositions: boolean;+};++/**+ * Organize canvas layout based on the requested mode.+ */+export function applyLayout(req: LayoutRequest): LayoutResult {+ switch (req.mode) {+ case "fresh":+ return {+ nodes: layoutWithDagre(req.nodes, req.edges),+ preservedExistingPositions: false,+ };+ case "focus":+ return {+ nodes: focusNodeLayout(req.focalId, req.nodes, req.edges),+ preservedExistingPositions: false,+ };+ case "merge": {+ const merged = mergeWithExistingPositions(+ req.incoming,+ req.current,+ req.edges,+ );+ if (merged != null) {+ return { nodes: merged, preservedExistingPositions: true };+ }+ return applyLayout({+ nodes: req.incoming,+ edges: req.edges,+ mode: "fresh",+ });+ }+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout.unit.spec.tsnew file mode 100644index 00000000000..b83949d6666--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout.unit.spec.ts@@ -0,0 +1,384 @@+import type { SchemaViewerFlowNode } from "../types";++import { applyLayout } from "./layout";+import { makeFlowNode } from "./test-utils";++type NodeOverrides = {+ fieldCount?: number;+ position?: { x: number; y: number };+ width?: number;+ height?: number;+};++// Layout tests assume non-empty tables by default — without rows, the table+// height collapses and overlap checks lose their signal.+function makeNode(+ id: string,+ overrides: NodeOverrides = {},+): SchemaViewerFlowNode {+ return makeFlowNode({ id, fieldCount: 2, ...overrides });+}++function placedNode(+ id: string,+ position: { x: number; y: number },+ overrides: NodeOverrides = {},+): SchemaViewerFlowNode {+ const node = makeNode(id, { ...overrides, position });+ return { ...node, style: { ...node.style, opacity: 1 } };+}++function rectsOverlap(+ a: { x: number; y: number; w: number; h: number },+ b: { x: number; y: number; w: number; h: number },+): boolean {+ return (+ a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y+ );+}++describe("applyLayout — fresh mode", () => {+ it("positions every node and reports no preserved positions", () => {+ const nodes = [+ makeNode("table-1"),+ makeNode("table-2"),+ makeNode("table-3"),+ ];+ const edges = [+ { source: "table-1", target: "table-2" },+ { source: "table-2", target: "table-3" },+ ];++ const result = applyLayout({ mode: "fresh", nodes, edges });++ expect(result.preservedExistingPositions).toBe(false);+ expect(result.nodes).toHaveLength(3);+ for (const node of result.nodes) {+ expect(node.style?.opacity).toBe(1);+ expect(typeof node.style?.width).toBe("number");+ expect(typeof node.style?.height).toBe("number");+ }+ // All node ids preserved+ expect(result.nodes.map((n) => n.id).sort()).toEqual([+ "table-1",+ "table-2",+ "table-3",+ ]);+ });++ it("produces non-overlapping bounding boxes for connected nodes", () => {+ const nodes = [+ makeNode("table-1"),+ makeNode("table-2"),+ makeNode("table-3"),+ ];+ const edges = [+ { source: "table-1", target: "table-2" },+ { source: "table-2", target: "table-3" },+ ];++ const result = applyLayout({ mode: "fresh", nodes, edges });++ const rects = result.nodes.map((n) => ({+ x: n.position.x,+ y: n.position.y,+ w: Number(n.style?.width),+ h: Number(n.style?.height),+ }));+ for (let i = 0; i < rects.length; i++) {+ for (let j = i + 1; j < rects.length; j++) {+ expect(rectsOverlap(rects[i], rects[j])).toBe(false);+ }+ }+ });++ it("handles a single node", () => {+ const result = applyLayout({+ mode: "fresh",+ nodes: [makeNode("table-1")],+ edges: [],+ });+ expect(result.nodes).toHaveLength(1);+ expect(result.nodes[0].style?.opacity).toBe(1);+ });+});++describe("applyLayout — merge mode", () => {+ it("returns fresh layout when there is no existing canvas state", () => {+ const incoming = [makeNode("table-1"), makeNode("table-2")];+ const result = applyLayout({+ mode: "merge",+ incoming,+ current: [],+ edges: [{ source: "table-1", target: "table-2" }],+ });+ expect(result.preservedExistingPositions).toBe(false);+ expect(result.nodes).toHaveLength(2);+ // Fresh path adds opacity:1+ for (const node of result.nodes) {+ expect(node.style?.opacity).toBe(1);+ }+ });++ it("preserves existing positions when only adding a connected node", () => {+ const existing = placedNode("table-1", { x: 100, y: 200 });+ const newNode = makeNode("table-2");+ const result = applyLayout({+ mode: "merge",+ incoming: [existing, newNode],+ current: [existing],+ edges: [{ source: "table-1", target: "table-2" }],+ });++ expect(result.preservedExistingPositions).toBe(true);+ expect(result.nodes).toHaveLength(2);++ const preserved = result.nodes.find((n) => n.id === "table-1")!;+ expect(preserved.position).toEqual({ x: 100, y: 200 });++ const placed = result.nodes.find((n) => n.id === "table-2")!;+ expect(placed.style?.opacity).toBe(1);+ });++ it("places a new node without overlapping the existing neighbor", () => {+ const existing = placedNode("table-1", { x: 0, y: 0 });+ const newNode = makeNode("table-2");+ const result = applyLayout({+ mode: "merge",+ incoming: [existing, newNode],+ current: [existing],+ edges: [{ source: "table-1", target: "table-2" }],+ });++ const a = result.nodes.find((n) => n.id === "table-1")!;+ const b = result.nodes.find((n) => n.id === "table-2")!;+ expect(+ rectsOverlap(+ {+ x: a.position.x,+ y: a.position.y,+ w: Number(a.style?.width),+ h: Number(a.style?.height),+ },+ {+ x: b.position.x,+ y: b.position.y,+ w: Number(b.style?.width),+ h: Number(b.style?.height),+ },+ ),+ ).toBe(false);+ });++ it("places a target-side new node to the right of its source neighbor", () => {+ const existing = placedNode("table-1", { x: 0, y: 0 });+ const newNode = makeNode("table-2");+ const result = applyLayout({+ mode: "merge",+ incoming: [existing, newNode],+ current: [existing],+ edges: [{ source: "table-1", target: "table-2" }],+ });+ const placed = result.nodes.find((n) => n.id === "table-2")!;+ // edge source=existing, new=target → new node prefers the right column.+ expect(placed.position.x).toBeGreaterThan(existing.position.x);+ });++ it("preserves the incoming node order", () => {+ const a = placedNode("table-1", { x: 0, y: 0 });+ const b = placedNode("table-2", { x: 1000, y: 0 });+ const c = makeNode("table-3");+ const incoming = [c, a, b];+ const result = applyLayout({+ mode: "merge",+ incoming,+ current: [a, b],+ edges: [+ { source: "table-1", target: "table-2" },+ { source: "table-1", target: "table-3" },+ ],+ });+ expect(result.nodes.map((n) => n.id)).toEqual([+ "table-3",+ "table-1",+ "table-2",+ ]);+ });++ it("falls back to fresh layout when an existing node was removed", () => {+ const a = placedNode("table-1", { x: 0, y: 0 });+ const b = placedNode("table-2", { x: 1000, y: 0 });+ const result = applyLayout({+ mode: "merge",+ // b dropped from incoming → not a pure add+ incoming: [a],+ current: [a, b],+ edges: [],+ });+ expect(result.preservedExistingPositions).toBe(false);+ expect(result.nodes).toHaveLength(1);+ });++ it("falls back to fresh layout when a new node has no edge to anything existing", () => {+ const existing = placedNode("table-1", { x: 0, y: 0 });+ const orphan = makeNode("table-2");+ const result = applyLayout({+ mode: "merge",+ incoming: [existing, orphan],+ current: [existing],+ edges: [], // orphan has no neighbor+ });+ expect(result.preservedExistingPositions).toBe(false);+ });++ it("returns the no-op preserve result when incoming === current ids", () => {+ const a = placedNode("table-1", { x: 100, y: 200 });+ const b = placedNode("table-2", { x: 600, y: 200 });+ const result = applyLayout({+ mode: "merge",+ incoming: [a, b],+ current: [a, b],+ edges: [{ source: "table-1", target: "table-2" }],+ });+ expect(result.preservedExistingPositions).toBe(true);+ expect(result.nodes.find((n) => n.id === "table-1")?.position).toEqual({+ x: 100,+ y: 200,+ });+ expect(result.nodes.find((n) => n.id === "table-2")?.position).toEqual({+ x: 600,+ y: 200,+ });+ });+});++describe("applyLayout — focus mode", () => {+ it("keeps the focal node at its current position", () => {+ const focal = placedNode("table-1", { x: 500, y: 500 });+ const out = makeNode("table-2");+ const result = applyLayout({+ mode: "focus",+ focalId: "table-1",+ nodes: [focal, out],+ edges: [{ source: "table-1", target: "table-2" }],+ });+ expect(result.nodes.find((n) => n.id === "table-1")?.position).toEqual({+ x: 500,+ y: 500,+ });+ });++ it("places outgoing neighbors to the right of the focal node", () => {+ const focal = placedNode("table-1", { x: 500, y: 500 });+ const out1 = makeNode("table-2");+ const out2 = makeNode("table-3");+ const result = applyLayout({+ mode: "focus",+ focalId: "table-1",+ nodes: [focal, out1, out2],+ edges: [+ { source: "table-1", target: "table-2" },+ { source: "table-1", target: "table-3" },+ ],+ });+ const focalRight = focal.position.x + Number(focal.style?.width);+ for (const id of ["table-2", "table-3"]) {+ const placed = result.nodes.find((n) => n.id === id)!;+ expect(placed.position.x).toBeGreaterThanOrEqual(focalRight);+ }+ });++ it("places incoming neighbors to the left of the focal node", () => {+ const focal = placedNode("table-1", { x: 500, y: 500 });+ const inc1 = makeNode("table-2");+ const inc2 = makeNode("table-3");+ const result = applyLayout({+ mode: "focus",+ focalId: "table-1",+ nodes: [focal, inc1, inc2],+ edges: [+ { source: "table-2", target: "table-1" },+ { source: "table-3", target: "table-1" },+ ],+ });+ for (const id of ["table-2", "table-3"]) {+ const placed = result.nodes.find((n) => n.id === id)!;+ const placedRight = placed.position.x + Number(placed.style?.width);+ expect(placedRight).toBeLessThanOrEqual(focal.position.x);+ }+ });++ it("ignores self-references when partitioning neighbors", () => {+ const focal = placedNode("table-1", { x: 500, y: 500 });+ const result = applyLayout({+ mode: "focus",+ focalId: "table-1",+ nodes: [focal],+ edges: [{ source: "table-1", target: "table-1" }],+ });+ expect(result.nodes).toHaveLength(1);+ expect(result.nodes[0].position).toEqual({ x: 500, y: 500 });+ });++ it("returns nodes unchanged when the focal node is not in the input", () => {+ const a = placedNode("table-1", { x: 0, y: 0 });+ const b = placedNode("table-2", { x: 1000, y: 0 });+ const result = applyLayout({+ mode: "focus",+ focalId: "table-99",+ nodes: [a, b],+ edges: [{ source: "table-1", target: "table-2" }],+ });+ expect(result.nodes.find((n) => n.id === "table-1")?.position).toEqual({+ x: 0,+ y: 0,+ });+ expect(result.nodes.find((n) => n.id === "table-2")?.position).toEqual({+ x: 1000,+ y: 0,+ });+ });++ it("places disconnected nodes without overlapping the focal cluster", () => {+ const focal = placedNode("table-1", { x: 0, y: 0 });+ const out = makeNode("table-2");+ const orphan = makeNode("table-3");+ const result = applyLayout({+ mode: "focus",+ focalId: "table-1",+ nodes: [focal, out, orphan],+ edges: [{ source: "table-1", target: "table-2" }],+ });+ const rects = result.nodes.map((n) => ({+ x: n.position.x,+ y: n.position.y,+ w: Number(n.style?.width),+ h: Number(n.style?.height),+ }));+ for (let i = 0; i < rects.length; i++) {+ for (let j = i + 1; j < rects.length; j++) {+ expect(rectsOverlap(rects[i], rects[j])).toBe(false);+ }+ }+ });++ it("preserves the original node order in the result", () => {+ const focal = placedNode("table-1", { x: 0, y: 0 });+ const a = makeNode("table-2");+ const b = makeNode("table-3");+ const result = applyLayout({+ mode: "focus",+ focalId: "table-1",+ nodes: [a, focal, b],+ edges: [+ { source: "table-1", target: "table-2" },+ { source: "table-1", target: "table-3" },+ ],+ });+ expect(result.nodes.map((n) => n.id)).toEqual([+ "table-2",+ "table-1",+ "table-3",+ ]);+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/constants.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/constants.tsnew file mode 100644index 00000000000..0726c4479c1--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/constants.ts@@ -0,0 +1,16 @@+/**+ * Dagre's algorithm is the default positioning algorithm used by React Flow.+ * The algorithm parameters used for spacing nodes in the SchemaViewer's graph layout:+ *+ * DAGRE_NODE_SEP_PX - Minimum horizontal separation between nodes on the same rank (row). Controls how far apart adjacent tables are positioned horizontally.+ * DAGRE_RANK_SEP_PX - Minimum vertical separation between ranks (rows). Controls the vertical spacing between different levels of the dependency graph.+ */+export const DAGRE_NODE_SEP_PX = 60;+export const DAGRE_RANK_SEP_PX = 120;++// Minimum visual gap to leave between a newly-placed node and any existing one+export const COLLISION_PADDING_PX = 20;+// Vertical step used when walking to find a free slot for an incoming node+export const COLLISION_Y_STEP_PX = 100;+// Maximum number of Y steps to try before giving up on a given column+export const MAX_COLLISION_Y_STEPS = 40;diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/dagre-layout.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/dagre-layout.tsnew file mode 100644index 00000000000..23720337c0e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/dagre-layout.ts@@ -0,0 +1,56 @@+import dagre from "@dagrejs/dagre";++import { NODE_WIDTH_PX } from "../../constants";+import type { SchemaViewerFlowNode } from "../../types";+import { getNodeHeight } from "../flow-graph";++import { DAGRE_NODE_SEP_PX, DAGRE_RANK_SEP_PX } from "./constants";+import type { LayoutEdge } from "./types";++/**+ * Runs a full Dagre pass and converts center-based Dagre coordinates into+ * React Flow's top-left node positions.+ */+export function layoutWithDagre(+ nodes: SchemaViewerFlowNode[],+ edges: LayoutEdge[],+): SchemaViewerFlowNode[] {+ const dagreGraph = new dagre.graphlib.Graph();+ dagreGraph.setGraph({+ rankdir: "LR",+ nodesep: DAGRE_NODE_SEP_PX,+ ranksep: DAGRE_RANK_SEP_PX,+ });+ dagreGraph.setDefaultEdgeLabel(() => ({}));++ nodes.forEach((node) => {+ dagreGraph.setNode(node.id, {+ width: NODE_WIDTH_PX,+ height: getNodeHeight(node.data.fields?.length ?? 0),+ });+ });++ edges.forEach((edge) => {+ dagreGraph.setEdge(edge.source, edge.target);+ });++ dagre.layout(dagreGraph);++ return nodes.map((node) => {+ const { x, y, width, height } = dagreGraph.node(node.id);+ return {+ ...node,+ position: {+ x: x - width / 2,+ y: y - height / 2,+ },+ // Sync dimensions with React Flow's internal state+ style: {+ ...node.style,+ width,+ height,+ opacity: 1, // Show after positioning+ },+ };+ });+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/focal-layout.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/focal-layout.tsnew file mode 100644index 00000000000..2675a03fb64--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/focal-layout.ts@@ -0,0 +1,138 @@+import { NODE_WIDTH_PX } from "../../constants";+import type { SchemaViewerFlowNode } from "../../types";++import { DAGRE_NODE_SEP_PX, DAGRE_RANK_SEP_PX } from "./constants";+import { layoutWithDagre } from "./dagre-layout";+import { partitionFocalNeighbors } from "./graph-neighborhood";+import type { PlacementCanvas } from "./placement-canvas";+import { createPlacementCanvas } from "./placement-canvas";+import type { LayoutEdge } from "./types";++/**+ * Stacks direct focal neighbors vertically in a single column centered on the+ * focal node, preserving the neighbor iteration order.+ */+function placeFocalNeighborColumn(+ neighborIds: Set<string>,+ x: number,+ focalCenterY: number,+ canvas: PlacementCanvas,+): void {+ const neighbors: { node: SchemaViewerFlowNode; height: number }[] = [];+ let totalHeight = 0;+ for (const id of neighborIds) {+ const node = canvas.getNode(id);+ if (node != null) {+ const height = canvas.getDimensions(node).height;+ neighbors.push({ node, height });+ totalHeight += height;+ }+ }+ if (neighbors.length === 0) {+ return;+ }+ totalHeight += DAGRE_NODE_SEP_PX * (neighbors.length - 1);+ let cursorY = focalCenterY - totalHeight / 2;+ for (const { node, height } of neighbors) {+ canvas.place(node, { x, y: cursorY });+ cursorY += height + DAGRE_NODE_SEP_PX;+ }+}++/**+ * Lays out everything that isn't part of the focal cluster (indirect nodes ++ * fully disconnected ones) with Dagre as an independent side cluster, then+ * translates the cluster one extra rank-gap to the right of the already-placed+ * focal content and vertically centers it on the focal node. Cross-cluster+ * edges (focal-cluster ↔ side-cluster) are intentionally excluded from the+ * side Dagre call so the side cluster's internal shape is driven by its own+ * connectivity, not pulled toward the already-placed focal cluster.+ */+function placeFocalSideCluster(+ restNodes: SchemaViewerFlowNode[],+ edges: LayoutEdge[],+ focalCenterY: number,+ canvas: PlacementCanvas,+): void {+ if (restNodes.length === 0) {+ return;+ }+ const restIds = new Set<string>();+ for (const node of restNodes) {+ restIds.add(node.id);+ }+ const restEdges = edges.filter(+ (e) => restIds.has(e.source) && restIds.has(e.target),+ );+ const laidOutRest = layoutWithDagre(restNodes, restEdges);++ let restMinX = Infinity;+ let restMinY = Infinity;+ let restMaxY = -Infinity;+ for (const node of laidOutRest) {+ const { height } = canvas.getDimensions(node);+ if (node.position.x < restMinX) {+ restMinX = node.position.x;+ }+ if (node.position.y < restMinY) {+ restMinY = node.position.y;+ }+ if (node.position.y + height > restMaxY) {+ restMaxY = node.position.y + height;+ }+ }++ const dx = canvas.rightEdge + DAGRE_RANK_SEP_PX * 2 - restMinX;+ const dy = focalCenterY - (restMinY + restMaxY) / 2;++ for (const node of laidOutRest) {+ canvas.place(node, {+ x: node.position.x + dx,+ y: node.position.y + dy,+ });+ }+}++/**+ * Re-layouts the graph around a focal node without moving the focal node+ * itself, so the user's camera position remains meaningful. Direct incoming+ * neighbors are stacked in a centered column on the left, direct outgoing+ * neighbors are stacked on the right.+ * Everything outside that focal cluster is laid out with Dagre as+ * an independent side cluster.+ */+export function focusNodeLayout(+ focalId: string,+ nodes: SchemaViewerFlowNode[],+ edges: LayoutEdge[],+): SchemaViewerFlowNode[] {+ const canvas = createPlacementCanvas(nodes);+ const focal = canvas.getNode(focalId);+ if (focal == null) {+ return nodes;+ }++ canvas.place(focal, focal.position);+ const { width: focalWidth, height: focalHeight } =+ canvas.getDimensions(focal);+ const focalCenterY = focal.position.y + focalHeight / 2;++ const { incomingIds, outgoingIds } = partitionFocalNeighbors(focalId, edges);+ placeFocalNeighborColumn(+ incomingIds,+ focal.position.x - NODE_WIDTH_PX - DAGRE_RANK_SEP_PX,+ focalCenterY,+ canvas,+ );+ placeFocalNeighborColumn(+ outgoingIds,+ focal.position.x + focalWidth + DAGRE_RANK_SEP_PX,+ focalCenterY,+ canvas,+ );++ const restNodes = nodes.filter((n) => !canvas.hasPlaced(n.id));+ placeFocalSideCluster(restNodes, edges, focalCenterY, canvas);++ return canvas.getPlacedOrOriginalNodesInOrder(nodes);+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/graph-neighborhood.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/graph-neighborhood.tsnew file mode 100644index 00000000000..748ae0bc6b9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/graph-neighborhood.ts@@ -0,0 +1,55 @@+import type { LayoutEdge, NeighborPlacement } from "./types";++/**+ * Creates bidirectional neighbor lookup for incremental placement, preserving+ * edge direction as a preferred left/right placement hint.+ */+export function buildAdjacency(+ edges: LayoutEdge[],+): Map<string, NeighborPlacement[]> {+ const adjacency = new Map<string, NeighborPlacement[]>();+ for (const edge of edges) {+ const sourceNeighbors = adjacency.get(edge.source);+ const targetNeighbors = adjacency.get(edge.target);+ const sourcePlacement = {+ neighborId: edge.target,+ preferredSide: "left" as const,+ };+ const targetPlacement = {+ neighborId: edge.source,+ preferredSide: "right" as const,+ };+ if (sourceNeighbors == null) {+ adjacency.set(edge.source, [sourcePlacement]);+ } else {+ sourceNeighbors.push(sourcePlacement);+ }+ if (targetNeighbors == null) {+ adjacency.set(edge.target, [targetPlacement]);+ } else {+ targetNeighbors.push(targetPlacement);+ }+ }+ return adjacency;+}++/**+ * Splits edges incident to the focal node into incoming and outgoing neighbor+ * sets. Self-referential edges are dropped so the focal node never appears in+ * its own neighbor columns.+ */+export function partitionFocalNeighbors(+ focalId: string,+ edges: LayoutEdge[],+): { incomingIds: Set<string>; outgoingIds: Set<string> } {+ const incomingIds = new Set<string>();+ const outgoingIds = new Set<string>();+ for (const edge of edges) {+ if (edge.source === focalId && edge.target !== focalId) {+ outgoingIds.add(edge.target);+ } else if (edge.target === focalId && edge.source !== focalId) {+ incomingIds.add(edge.source);+ }+ }+ return { incomingIds, outgoingIds };+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/incremental-layout.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/incremental-layout.tsnew file mode 100644index 00000000000..a5497ffaf0d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/incremental-layout.ts@@ -0,0 +1,108 @@+import type { SchemaViewerFlowNode } from "../../types";++import { buildAdjacency } from "./graph-neighborhood";+import type { PlacementCanvas } from "./placement-canvas";+import { createPlacementCanvas } from "./placement-canvas";+import type { LayoutEdge, NeighborPlacement } from "./types";++/**+ * Merge incoming graph nodes with currently-positioned nodes, preserving the+ * positions of tables that were already on the canvas and placing genuinely+ * new tables next to a connected existing neighbor without overlapping any+ * other node. Returns null if the incoming graph can't be merged+ * incrementally — in which case the caller should+ * fall back to the fresh `incoming` nodes and let the normal Dagre layout+ * path handle them.+ */+export function mergeWithExistingPositions(+ incoming: SchemaViewerFlowNode[],+ current: SchemaViewerFlowNode[],+ edges: LayoutEdge[],+): SchemaViewerFlowNode[] | null {+ if (current.length === 0) {+ return null;+ }++ const currentById = new Map<string, SchemaViewerFlowNode>();+ for (const node of current) {+ currentById.set(node.id, node);+ }++ const incomingIds = new Set<string>();+ for (const node of incoming) {+ incomingIds.add(node.id);+ }++ // If any existing node was removed, this isn't a pure add — fall back.+ // (this shouldn't happen in theory)+ if (current.some((n) => !incomingIds.has(n.id))) {+ return null;+ }++ const canvas = createPlacementCanvas(incoming);+ const newNodes: SchemaViewerFlowNode[] = [];+ for (const node of incoming) {+ const existing = currentById.get(node.id);+ if (existing != null) {+ canvas.preserve(node, existing);+ } else {+ newNodes.push(node);+ }+ }++ if (newNodes.length === 0) {+ return canvas.getPlacedNodesInOrder(incoming);+ }++ const adjacency = buildAdjacency(edges);+ const remaining = placeReachableAdditions(newNodes, adjacency, canvas);++ // If any new node has no reachable neighbor in the current graph - fall back.+ if (remaining.length > 0) {+ return null;+ }++ // Return nodes in the incoming order so edge ordering stays consistent.+ return canvas.getPlacedNodesInOrder(incoming);+}++/**+ * Places nodes whose neighbors are already positioned, iterating until no+ * reachable unplaced nodes remain.+ *+ * Each pass scans the currently unplaced nodes and looks for the first+ * adjacency entry that points to an already placed neighbor. When one is found,+ * the node is positioned next to that neighbor on the preferred side.+ * Nodes without any placed neighbors are carried forward.+ * The loop stops once a full pass cannot place anything, leaving only+ * nodes that are disconnected from the placed component.+ */+function placeReachableAdditions(+ nodes: SchemaViewerFlowNode[],+ adjacency: Map<string, NeighborPlacement[]>,+ canvas: PlacementCanvas,+): SchemaViewerFlowNode[] {+ let remaining = nodes;+ let progressed = true;+ while (remaining.length > 0 && progressed) {+ progressed = false;+ const stillRemaining: SchemaViewerFlowNode[] = [];+ for (const node of remaining) {+ const placement = adjacency+ .get(node.id)+ ?.find(({ neighborId }) => canvas.hasPlaced(neighborId));+ if (placement == null) {+ stillRemaining.push(node);+ continue;+ }+ const neighbor = canvas.getPlaced(placement.neighborId)!;+ canvas.place(+ node,+ canvas.findNearestOpenSlot(node, neighbor, placement.preferredSide),+ );+ progressed = true;+ }+ remaining = stillRemaining;+ }+ return remaining;+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/placement-canvas.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/placement-canvas.tsnew file mode 100644index 00000000000..879f336a196--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/placement-canvas.ts@@ -0,0 +1,316 @@+import { HEADER_HEIGHT_PX, NODE_WIDTH_PX } from "../../constants";+import type { SchemaViewerFlowNode } from "../../types";++import {+ COLLISION_PADDING_PX,+ COLLISION_Y_STEP_PX,+ DAGRE_RANK_SEP_PX,+ MAX_COLLISION_Y_STEPS,+} from "./constants";+import type { NodeDimensions, PlacementSide } from "./types";++type OccupiedBox = {+ left: number;+ right: number;+ top: number;+ bottom: number;+};++type OccupiedColumn = {+ left: number;+ right: number;+ boxes: OccupiedBox[];+};++/**+ * Owns the mutable placement state for one layout pass: which nodes have+ * already been positioned, their dimensions, and the spatial index used to+ * find non-overlapping slots for subsequent nodes.+ */+export class PlacementCanvas {+ private columns: OccupiedColumn[] = [];+ private columnsByX = new Map<number, OccupiedColumn>();+ private dimensionsById = new Map<string, NodeDimensions>();+ private nodesById = new Map<string, SchemaViewerFlowNode>();+ private placedById = new Map<string, SchemaViewerFlowNode>();+ private maxRight = 0;+ private maxColumnWidth = 0;++ constructor(nodes: SchemaViewerFlowNode[]) {+ for (const node of nodes) {+ this.nodesById.set(node.id, node);+ this.dimensionsById.set(node.id, getNodeDimensions(node));+ }+ }++ get rightEdge(): number {+ return this.maxRight;+ }++ getDimensions(node: SchemaViewerFlowNode): NodeDimensions {+ return getNodeDimensions(node, this.dimensionsById);+ }++ getNode(id: string): SchemaViewerFlowNode | undefined {+ return this.nodesById.get(id);+ }++ hasPlaced(id: string): boolean {+ return this.placedById.has(id);+ }++ getPlaced(id: string): SchemaViewerFlowNode | undefined {+ return this.placedById.get(id);+ }++ getPlacedNodesInOrder(nodes: SchemaViewerFlowNode[]): SchemaViewerFlowNode[] {+ return nodes.map((node) => this.placedById.get(node.id)!);+ }++ getPlacedOrOriginalNodesInOrder(+ nodes: SchemaViewerFlowNode[],+ ): SchemaViewerFlowNode[] {+ return nodes.map((node) => this.placedById.get(node.id) ?? node);+ }++ place(+ node: SchemaViewerFlowNode,+ position: { x: number; y: number },+ ): SchemaViewerFlowNode {+ const positionedNode = {+ ...node,+ position,+ style: {+ ...node.style,+ opacity: 1,+ },+ };+ this.registerPlacedNode(positionedNode);+ return positionedNode;+ }++ preserve(+ node: SchemaViewerFlowNode,+ existing: SchemaViewerFlowNode,+ ): SchemaViewerFlowNode {+ const positionedNode = {+ ...node,+ position: existing.position,+ style: existing.style,+ };+ this.registerPlacedNode(positionedNode);+ return positionedNode;+ }++ private registerPlacedNode(node: SchemaViewerFlowNode): void {+ this.placedById.set(node.id, node);+ const { width, height } = this.getDimensions(node);+ const x = node.position.x;+ const y = node.position.y;+ const occupied: OccupiedBox = {+ left: x,+ right: x + width,+ top: y,+ bottom: y + height,+ };+ const column = this.columnsByX.get(x);+ if (column == null) {+ const newColumn = {+ left: occupied.left,+ right: occupied.right,+ boxes: [occupied],+ };+ this.columnsByX.set(x, newColumn);+ insertColumn(newColumn, this.columns);+ } else {+ column.right = Math.max(column.right, occupied.right);+ column.boxes.push(occupied);+ }+ this.maxRight = Math.max(this.maxRight, occupied.right);+ this.maxColumnWidth = Math.max(this.maxColumnWidth, width);+ }++ /**+ * Find a position for a new node next to a connected neighbor such that the+ * resulting bounding box doesn't overlap any already-placed node. Strategy:+ * walk outward from the neighbor's (x, y), preferring positions that are+ * close to the neighbor — interleaving the "preferred" side (the Dagre+ * rankdir convention) with the "alternate" side at each Y step so that+ * same-row placement on either side wins over a far-away Y on the preferred+ * column. Falls back to a fresh column to the right of all existing+ * content if nothing fits within the search window.+ */+ findNearestOpenSlot(+ newNode: SchemaViewerFlowNode,+ neighbor: SchemaViewerFlowNode,+ preferredSide: PlacementSide,+ ): { x: number; y: number } {+ const { width, height } = this.getDimensions(newNode);+ const preferredX = getAdjacentX(newNode, neighbor, preferredSide, this);+ const alternateX = getAdjacentX(+ newNode,+ neighbor,+ preferredSide === "right" ? "left" : "right",+ this,+ );+ const baseY = neighbor.position.y;++ const fits = (x: number, y: number) =>+ !this.collidesWithAny(x, y, width, height);++ // Try increasing Y offsets, checking both columns at each step. Within a+ // given Y step, preferred side is checked before alternate. For i > 0 we+ // try the +Y direction before the -Y direction (downward bias matches the+ // Dagre layout's tendency to grow downward on relayouts).+ for (let i = 0; i <= MAX_COLLISION_Y_STEPS; i++) {+ if (i === 0) {+ if (fits(preferredX, baseY)) {+ return { x: preferredX, y: baseY };+ }+ if (fits(alternateX, baseY)) {+ return { x: alternateX, y: baseY };+ }+ continue;+ }+ const dy = i * COLLISION_Y_STEP_PX;+ if (fits(preferredX, baseY + dy)) {+ return { x: preferredX, y: baseY + dy };+ }+ if (fits(alternateX, baseY + dy)) {+ return { x: alternateX, y: baseY + dy };+ }+ if (fits(preferredX, baseY - dy)) {+ return { x: preferredX, y: baseY - dy };+ }+ if (fits(alternateX, baseY - dy)) {+ return { x: alternateX, y: baseY - dy };+ }+ }++ // Last resort: fresh column to the right of everything.+ return { x: this.maxRight + DAGRE_RANK_SEP_PX, y: baseY };+ }++ /**+ * Tests a candidate box against nearby occupied columns, using the sorted+ * column index to skip boxes that cannot overlap horizontally.+ */+ private collidesWithAny(+ x: number,+ y: number,+ width: number,+ height: number,+ ): boolean {+ const left = x;+ const right = x + width;+ const top = y;+ const bottom = y + height;+ const firstColumn = getFirstColumnAtOrAfter(+ this.columns,+ left - this.maxColumnWidth - COLLISION_PADDING_PX,+ );++ for (let i = firstColumn; i < this.columns.length; i++) {+ const column = this.columns[i];+ if (column.left >= right + COLLISION_PADDING_PX) {+ break;+ }+ if (left >= column.right + COLLISION_PADDING_PX) {+ continue;+ }+ for (const box of column.boxes) {+ if (+ left < box.right + COLLISION_PADDING_PX &&+ right + COLLISION_PADDING_PX > box.left &&+ top < box.bottom + COLLISION_PADDING_PX &&+ bottom + COLLISION_PADDING_PX > box.top+ ) {+ return true;+ }+ }+ }+ return false;+ }+}++export function createPlacementCanvas(+ nodes: SchemaViewerFlowNode[],+): PlacementCanvas {+ return new PlacementCanvas(nodes);+}++function getAdjacentX(+ newNode: SchemaViewerFlowNode,+ neighbor: SchemaViewerFlowNode,+ side: PlacementSide,+ canvas: PlacementCanvas,+): number {+ const { width } = canvas.getDimensions(newNode);+ const { width: neighborWidth } = canvas.getDimensions(neighbor);+ return side === "right"+ ? neighbor.position.x + neighborWidth + DAGRE_RANK_SEP_PX+ : neighbor.position.x - width - DAGRE_RANK_SEP_PX;+}++/**+ * Reads numeric dimensions that React Flow stores on node style; ignores+ * non-numeric style values so callers can safely fall back.+ */+function getStyleDimension(+ node: SchemaViewerFlowNode,+ key: "width" | "height",+): number | null {+ const value = node.style?.[key];+ return typeof value === "number" ? value : null;+}++/**+ * Resolves dimensions from the placement cache first, falling back to style+ * dimensions and then default table-card dimensions.+ */+function getNodeDimensions(+ node: SchemaViewerFlowNode,+ dimensionsById?: Map<string, NodeDimensions>,+): NodeDimensions {+ return (+ dimensionsById?.get(node.id) ?? {+ width: getStyleDimension(node, "width") ?? NODE_WIDTH_PX,+ height: getStyleDimension(node, "height") ?? HEADER_HEIGHT_PX,+ }+ );+}++/**+ * Inserts a new occupied column into sorted order, using an append fast path+ * for the common left-to-right layout case.+ */+function insertColumn(column: OccupiedColumn, columns: OccupiedColumn[]): void {+ const lastColumn = columns[columns.length - 1];+ if (lastColumn == null || lastColumn.left <= column.left) {+ columns.push(column);+ return;+ }++ columns.splice(getFirstColumnAtOrAfter(columns, column.left), 0, column);+}++/**+ * Finds the first column whose left edge is at or after a target X using a+ * lower-bound binary search.+ */+function getFirstColumnAtOrAfter(+ columns: OccupiedColumn[],+ minLeft: number,+): number {+ let low = 0;+ let high = columns.length;+ while (low < high) {+ const mid = Math.floor((low + high) / 2);+ if (columns[mid].left < minLeft) {+ low = mid + 1;+ } else {+ high = mid;+ }+ }+ return low;+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/types.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/types.tsnew file mode 100644index 00000000000..5046a8bba9d--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/layout/types.ts@@ -0,0 +1,13 @@+export type LayoutEdge = { source: string; target: string };++export type NodeDimensions = {+ width: number;+ height: number;+};++export type PlacementSide = "left" | "right";++export type NeighborPlacement = {+ neighborId: string;+ preferredSide: PlacementSide;+};diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/test-utils.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/test-utils.tsnew file mode 100644index 00000000000..ff4c423d0a3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/test-utils.ts@@ -0,0 +1,76 @@+import { HEADER_HEIGHT_PX, NODE_WIDTH_PX, ROW_HEIGHT_PX } from "../constants";+import type { SchemaViewerFlowNode } from "../types";++export type FlowNodeFieldSpec = { name: string; isFK?: boolean };++export type MakeFlowNodeOpts = {+ /** Numeric → `table-N`; string → used as-is. `data.table_id` is derived+ * from the numeric form (digits-only when a string is passed). */+ id: number | string;+ /** Display name; defaults to the string form of `id`. */+ name?: string;+ /** Explicit fields. Takes precedence over `fieldCount`. */+ fields?: FlowNodeFieldSpec[];+ /** Generate N placeholder fields named `f1`, `f2`, …. Defaults to 0. */+ fieldCount?: number;+ position?: { x: number; y: number };+ width?: number;+ height?: number;+ opacity?: number;+};++export function makeFlowNode({+ id,+ name,+ fields,+ fieldCount,+ position = { x: 0, y: 0 },+ width = NODE_WIDTH_PX,+ height,+ opacity = 0,+}: MakeFlowNodeOpts): SchemaViewerFlowNode {+ const idString = typeof id === "number" ? `table-${id}` : id;+ const tableId =+ typeof id === "number" ? id : Number(id.replace(/\D/g, "")) || 1;+ const displayName = name ?? idString;++ const resolvedFields: FlowNodeFieldSpec[] =+ fields ??+ Array.from({ length: fieldCount ?? 0 }, (_, i) => ({+ name: `f${i + 1}`,+ }));++ const computedHeight =+ height ?? HEADER_HEIGHT_PX + resolvedFields.length * ROW_HEIGHT_PX;++ return {+ id: idString,+ type: "schemaViewerTable",+ position,+ data: {+ table_id: tableId,+ name: displayName,+ display_name: displayName,+ description: null,+ owner: null,+ schema: "public",+ db_id: 1,+ fields: resolvedFields.map((f, i) => ({+ id: i + 1,+ name: f.name,+ display_name: f.name,+ database_type: "text",+ base_type: "type/Text",+ effective_type: "type/Text",+ semantic_type: f.isFK ? "type/FK" : null,+ fk_target_field_id: null,+ fk_target_table_id: null,+ })),+ sourceFieldIds: new Set<number>(),+ targetFieldIds: new Set<number>(),+ selfRefTargetFieldIds: new Set<number>(),+ selectedFieldIds: new Set<number>(),+ },+ style: { width, height: computedHeight, opacity },+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/zoom.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/zoom.tsnew file mode 100644index 00000000000..9b5f12d17f2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/utils/zoom.ts@@ -0,0 +1,82 @@+import type { ReactFlowInstance } from "@xyflow/react";++import { MAX_ZOOM, NODE_WIDTH_PX } from "../constants";+import type { SchemaViewerFlowEdge, SchemaViewerFlowNode } from "../types";++type ZoomTarget = Pick<+ ReactFlowInstance<SchemaViewerFlowNode, SchemaViewerFlowEdge>,+ "setCenter" | "getNodes"+>;++// (if this value changes, update the same constant in e2e/test/scenarios/schema-viewer/schema-viewer.cy.spec.ts)+const MIN_ZOOM_FOR_TARGET = 0.5;+// How far below the viewport's top edge the header of the topmost target+// node should land.+const TOP_MARGIN_PX = 50;+// Fractional horizontal padding applied to the bounding-box width when+// computing the width-based zoom level.+const HORIZONTAL_PADDING = 0.15;+// Animation duration for the camera pan/zoom.+export const ZOOM_DURATION_MS = 500;++/**+ * - Zoom is clamped to MIN_ZOOM_FOR_TARGET so tables+ * stay legible even for wide selections.+ * - Zoom is computed from the bounding-box WIDTH only. Height is+ * intentionally ignored so that tall tables don't force a low zoom; they+ * simply overflow the viewport vertically, which is fine as long as the+ * header stays visible.+ * - The camera is positioned so the TOP of the target bounding box+ * below the viewport's top edge, rather than centered.+ */+export function zoomToNode(instance: ZoomTarget, nodeId: string): boolean {+ if (!nodeId) {+ return false;+ }+ const target = instance.getNodes().find((n) => n.id === nodeId);+ if (!target) {+ return false;+ }++ const viewportEl = document.querySelector(".react-flow");+ const rect = viewportEl?.getBoundingClientRect();+ if (rect == null || rect.width === 0 || rect.height === 0) {+ return false;+ }++ // Bounding box of the target nodes in world coordinates.+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ const width =+ typeof target.style?.width === "number"+ ? target.style.width+ : NODE_WIDTH_PX;+ if (target.position.x < minX) {+ minX = target.position.x;+ }+ if (target.position.y < minY) {+ minY = target.position.y;+ }+ if (target.position.x + width > maxX) {+ maxX = target.position.x + width;+ }+ const bboxWidth = maxX - minX;++ const widthBasedZoom =+ rect.width / (bboxWidth * (1 + 2 * HORIZONTAL_PADDING));+ const zoom = Math.max(+ MIN_ZOOM_FOR_TARGET,+ Math.min(widthBasedZoom, MAX_ZOOM),+ );++ // Horizontally centered on the bbox.+ const centerX = (minX + maxX) / 2;+ // Vertically positioned so `minY` (the top of the topmost target, i.e.+ // the start of its header) lands TOP_MARGIN_PX from the viewport top+ // in screen space.+ const centerY = minY + (rect.height / 2 - TOP_MARGIN_PX) / zoom;++ instance.setCenter(centerX, centerY, { zoom, duration: ZOOM_DURATION_MS });+ return true;+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/index.tsnew file mode 100644index 00000000000..3de896543d3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/index.ts@@ -0,0 +1,12 @@+import { PLUGIN_SCHEMA_VIEWER } from "metabase/plugins";+import { hasPremiumFeature } from "metabase-enterprise/settings";++import { getDataStudioSchemaViewerRoutes } from "./routes";++export function initializePlugin() {+ if (hasPremiumFeature("schema-viewer")) {+ PLUGIN_SCHEMA_VIEWER.isEnabled = true;+ PLUGIN_SCHEMA_VIEWER.getDataStudioSchemaViewerRoutes =+ getDataStudioSchemaViewerRoutes;+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/SchemaViewerPage.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/SchemaViewerPage.tsxnew file mode 100644index 00000000000..4eabbc2e6b5--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/SchemaViewerPage.tsx@@ -0,0 +1,86 @@+import type { Location } from "history";+import { useMemo } from "react";+import { t } from "ttag";++import { skipToken } from "metabase/api";+import { usePageTitle } from "metabase/hooks/use-page-title";+import { Stack } from "metabase/ui";+import { getSchemaViewerParams } from "metabase/urls";+import { useGetErdQuery } from "metabase-enterprise/api";+import type { ConcreteTableId, DatabaseId } from "metabase-types/api";++import { SchemaViewer } from "../../components/SchemaViewer";+import { useSchemaPreferencesStore } from "../../components/SchemaViewer/hooks/useSchemaPreferencesStore";++import { useRedirectToLastDatabase } from "./useRedirectToLastDatabase";++type SchemaViewerPageQuery = {+ "database-id"?: string;+ "table-ids"?: string | string[];+ schema?: string;+};++type SchemaViewerPageProps = {+ location?: Location<SchemaViewerPageQuery>;+};++export function SchemaViewerPage({ location }: SchemaViewerPageProps) {+ usePageTitle(t`Schema viewer`);++ const rawDatabaseId = location?.query?.["database-id"];+ const rawTableIds = location?.query?.["table-ids"];+ const schema = location?.query?.schema;++ const databaseId: DatabaseId | undefined =+ rawDatabaseId != null ? Number(rawDatabaseId) : undefined;++ const tableIds: ConcreteTableId[] | undefined = useMemo(() => {+ if (rawTableIds == null) {+ return undefined;+ }+ const ids = Array.isArray(rawTableIds) ? rawTableIds : [rawTableIds];+ return ids.map(Number);+ }, [rawTableIds]);++ useRedirectToLastDatabase({ databaseId, schema });++ const { extraTableIds, addExtraTableId, contextKey, isRestoring } =+ useSchemaPreferencesStore({+ databaseId,+ schema,+ initialTableIds: tableIds,+ });++ // Defer the ERD query until per-context saved prefs have resolved — without+ // this gate we'd fire two requests on every schema entry: one with empty+ // `extraTableIds`, then another once the restored set arrives.+ const { data, isFetching, error } = useGetErdQuery(+ databaseId != null && !isRestoring+ ? getSchemaViewerParams({+ databaseId,+ schema,+ tableIds: extraTableIds,+ })+ : skipToken,+ );++ // Deep-link focal table: if the URL pins exactly one table-id, SchemaViewer+ // zooms to it after the first layout instead of fitting the whole canvas.+ const focalTableId =+ tableIds != null && tableIds.length === 1 ? tableIds[0] : null;++ return (+ <Stack h="100%">+ <SchemaViewer+ databaseId={databaseId}+ schema={schema}+ focalTableId={focalTableId}+ onExtraTableIdAdd={addExtraTableId}+ contextKey={contextKey}+ data={data}+ isFetching={isFetching}+ error={error}+ />+ </Stack>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/index.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/index.tsnew file mode 100644index 00000000000..f09f4d4f03e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/index.ts@@ -0,0 +1 @@+export { SchemaViewerPage } from "./SchemaViewerPage";diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/useRedirectToLastDatabase.ts b/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/useRedirectToLastDatabase.tsnew file mode 100644index 00000000000..9ebd7943750--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/useRedirectToLastDatabase.ts@@ -0,0 +1,94 @@+import { useEffect, useMemo, useRef } from "react";+import { replace } from "react-router-redux";++import { useListDatabasesQuery } from "metabase/api";+import { useUserKeyValue } from "metabase/common/hooks/use-user-key-value";+import { useDispatch } from "metabase/redux";+import * as Urls from "metabase/urls";+import type { DatabaseId } from "metabase-types/api";++type UseRedirectToLastDatabaseArgs = {+ databaseId: DatabaseId | undefined;+ schema: string | undefined;+};++/**+ * Owns the `schema_viewer.last_database` UserKeyValue:+ *+ * - On landing without a URL `database-id`, redirects to the last opened+ * (database, schema). Validates the saved database still exists.+ * - Re-saves on every URL context change while a database is selected, so+ * the next landing picks up where the user left off.+ */+export function useRedirectToLastDatabase({+ databaseId,+ schema,+}: UseRedirectToLastDatabaseArgs) {+ const dispatch = useDispatch();++ const {+ value: lastDatabase,+ setValue: setLastDatabase,+ isLoading: isLoadingLastDatabase,+ } = useUserKeyValue({+ namespace: "schema_viewer",+ key: "last_database",+ });++ const { data: databasesResponse, isLoading: isLoadingDatabases } =+ useListDatabasesQuery();+ const databases = useMemo(+ () => databasesResponse?.data?.filter((db) => !db.is_saved_questions),+ [databasesResponse],+ );++ // Redirect to last opened database only on initial load (not when user+ // clears selection).+ const hasDbSelected = databaseId != null;+ const shoudlRedirectRef = useRef(true);++ useEffect(() => {+ if (!shoudlRedirectRef.current) {+ return;+ }+ if (+ !isLoadingLastDatabase &&+ !isLoadingDatabases &&+ !hasDbSelected &&+ lastDatabase != null &&+ databases != null+ ) {+ // Validate saved database still exists before redirecting.+ const dbExists = databases.some(+ (db) => db.id === lastDatabase.databaseId,+ );+ if (dbExists) {+ shoudlRedirectRef.current = false;+ const url = Urls.dataStudioSchemaViewer({+ databaseId: lastDatabase.databaseId,+ schema: lastDatabase.schema,+ });+ dispatch(replace(url));+ }+ }+ // Mark as "redirected" even if we didn't redirect (no saved db or db+ // doesn't exist) so we don't re-redirect when the user clears selection.+ if (!isLoadingLastDatabase && !isLoadingDatabases) {+ shoudlRedirectRef.current = false;+ }+ }, [+ isLoadingLastDatabase,+ isLoadingDatabases,+ hasDbSelected,+ lastDatabase,+ databases,+ dispatch,+ ]);++ // Save current database/schema as last opened.+ useEffect(() => {+ if (databaseId != null) {+ setLastDatabase({ databaseId, schema });+ }+ }, [databaseId, schema, setLastDatabase]);+}diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/routes.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/routes.tsxnew file mode 100644index 00000000000..12415a1bb0b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/routes.tsx@@ -0,0 +1,7 @@+import { IndexRoute } from "react-router";++import { SchemaViewerPage } from "./pages/SchemaViewerPage";++export function getDataStudioSchemaViewerRoutes() {+ return <IndexRoute component={SchemaViewerPage} />;+}diff --git a/frontend/src/metabase-lib/query/types.ts b/frontend/src/metabase-lib/query/types.tsindex a82a58d4b3a..e8261c7c00c 100644--- a/frontend/src/metabase-lib/query/types.ts+++ b/frontend/src/metabase-lib/query/types.ts@@ -642,6 +642,6 @@ export type ValidationError = { message: string };export type JsColumnTypeInfo = {base_type?: string;- effective_type?: string;+ effective_type?: string | null;semantic_type?: string | null;};diff --git a/frontend/src/metabase-lib/v1/types/utils/isa.ts b/frontend/src/metabase-lib/v1/types/utils/isa.tsindex aca9b0da4e0..1fb4230284f 100644--- a/frontend/src/metabase-lib/v1/types/utils/isa.ts+++ b/frontend/src/metabase-lib/v1/types/utils/isa.ts@@ -24,7 +24,7 @@ import type { DatasetColumn, TableId } from "metabase-types/api";* used by functions that only need type-checking properties.*/export interface FieldTypeInfo {- base_type?: string;+ base_type?: string | null;effective_type?: string | null;semantic_type?: string | null;}diff --git a/frontend/src/metabase-types/api/database.ts b/frontend/src/metabase-types/api/database.tsindex fe8431204da..aa008bfb56d 100644--- a/frontend/src/metabase-types/api/database.ts+++ b/frontend/src/metabase-types/api/database.ts@@ -1,5 +1,5 @@import type { ScheduleSettings } from "./settings";-import type { Table } from "./table";+import type { SchemaName, Table } from "./table";import type { ISO8601Time, LongTaskStatus } from ".";@@ -86,6 +86,9 @@ export interface Database extends DatabaseData {// Only appears in GET /api/database/:id"can-manage"?: boolean;tables?: Table[];+ // Populated when GET /api/database is called with include=schemas; lists+ // schema names that contain at least one readable table.+ schemas?: SchemaName[];}export interface DatabaseData {@@ -152,7 +155,7 @@ export type GetDatabaseHealthResponse =| { status: "error"; message: string; errors: unknown };export interface ListDatabasesRequest {- include?: "tables";+ include?: "tables" | "schemas";saved?: boolean;include_editable_data_model?: boolean;exclude_uneditable_details?: boolean;diff --git a/frontend/src/metabase-types/api/erd.ts b/frontend/src/metabase-types/api/erd.tsnew file mode 100644index 00000000000..da95d950166--- /dev/null+++ b/frontend/src/metabase-types/api/erd.ts@@ -0,0 +1,62 @@+import type {+ ConcreteTableId,+ DatabaseId,+ FieldId,+ SchemaName,+ Table,+ TableId,+} from "./";++export type ErdRelationship = "one-to-one" | "many-to-one";++// The ERD endpoint never traverses cards / saved-question virtual tables —+/// hence ConcreteTableId instead of TableId.+export type ErdField = {+ id: FieldId;+ name: string;+ display_name: string;+ database_type: string;+ base_type: string;+ effective_type: string | null;+ semantic_type: string | null;+ fk_target_field_id: FieldId | null;+ fk_target_table_id: ConcreteTableId | null;+};++export type ErdNode = {+ table_id: ConcreteTableId;+ name: string;+ display_name: string;+ description: string | null;+ owner: Table["owner"];+ schema: SchemaName | null;+ db_id: DatabaseId;+ fields: ErdField[];+};++export type ErdEdge = {+ source_table_id: ConcreteTableId;+ source_field_id: FieldId;+ target_table_id: ConcreteTableId;+ target_field_id: FieldId;+ relationship: ErdRelationship;+};++export type ErdResponse = {+ nodes: ErdNode[];+ edges: ErdEdge[];+};++/**+ * Backend semantics:+ * - With a `schema`, the backend returns all tables in that schema; we only+ * append `table-ids` for external tables the user has explicitly expanded+ * into.+ * - With no `schema` but explicit `table-ids`, those are the focal set.+ * - At least one of `schema` or `table-ids` must be provided.+ */+export type ErdParams = {+ "database-id": DatabaseId;+ "table-ids"?: TableId[];+ schema?: SchemaName;+};diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.tsindex 449b82c38a0..9a7e35c1371 100644--- a/frontend/src/metabase-types/api/index.ts+++ b/frontend/src/metabase-types/api/index.ts@@ -25,6 +25,7 @@ export * from "./email";export * from "./embed";export * from "./embedding-theme";export * from "./entity-id";+export * from "./erd";export * from "./field";export * from "./geojson";export * from "./group";diff --git a/frontend/src/metabase-types/api/mocks/erd.ts b/frontend/src/metabase-types/api/mocks/erd.tsnew file mode 100644index 00000000000..db50ffd13eb--- /dev/null+++ b/frontend/src/metabase-types/api/mocks/erd.ts@@ -0,0 +1,48 @@+import type {+ ErdEdge,+ ErdField,+ ErdNode,+ ErdResponse,+} from "metabase-types/api";++export const createMockErdField = (opts?: Partial<ErdField>): ErdField => ({+ id: 1,+ name: "f",+ display_name: "f",+ database_type: "text",+ base_type: "type/Text",+ effective_type: "type/Text",+ semantic_type: null,+ fk_target_field_id: null,+ fk_target_table_id: null,+ ...opts,+});++export const createMockErdNode = (opts?: Partial<ErdNode>): ErdNode => ({+ table_id: 1,+ name: "t1",+ display_name: "T1",+ description: null,+ owner: null,+ schema: "public",+ db_id: 1,+ fields: [],+ ...opts,+});++export const createMockErdEdge = (opts?: Partial<ErdEdge>): ErdEdge => ({+ source_table_id: 1,+ source_field_id: 10,+ target_table_id: 2,+ target_field_id: 20,+ relationship: "many-to-one",+ ...opts,+});++export const createMockErdResponse = (+ opts?: Partial<ErdResponse>,+): ErdResponse => ({+ nodes: [],+ edges: [],+ ...opts,+});diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.tsindex 701095a5f1f..81351d05139 100644--- a/frontend/src/metabase-types/api/mocks/index.ts+++ b/frontend/src/metabase-types/api/mocks/index.ts@@ -10,6 +10,7 @@ export * from "./database";export * from "./dataset";export * from "./dependencies";export * from "./document";+export * from "./erd";export * from "./field";export * from "./geojson";export * from "./group";diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.tsindex 335cd5615a2..f69e6182cbb 100644--- a/frontend/src/metabase-types/api/mocks/settings.ts+++ b/frontend/src/metabase-types/api/mocks/settings.ts@@ -102,6 +102,7 @@ export const createMockTokenFeatures = (audit_app: false,cache_granular_controls: false,dependencies: false,+ "schema-viewer": false,disable_password_login: false,cloud_custom_smtp: false,content_translation: false,diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex 2c8f5931759..14408cc0323 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -370,6 +370,7 @@ export const tokenFeatures = ["table_data_editing","remote_sync","dependencies",+ "schema-viewer","semantic_search","transforms-python","transforms-basic",diff --git a/frontend/src/metabase-types/api/table.ts b/frontend/src/metabase-types/api/table.tsindex 9d25586173c..2ec22b9ea8b 100644--- a/frontend/src/metabase-types/api/table.ts+++ b/frontend/src/metabase-types/api/table.ts@@ -74,7 +74,7 @@ export type Table = {data_layer: TableDataLayer | null;owner_email: string | null;owner_user_id: UserId | null;- owner?: TableOwner | null;+ owner?: TableOwner | { email: string } | null;estimated_row_count?: number | null;transform_id: TransformId | null; // readonlyview_count: number;diff --git a/frontend/src/metabase-types/api/user.ts b/frontend/src/metabase-types/api/user.tsindex 78a6ba062e2..dfa072a8d92 100644--- a/frontend/src/metabase-types/api/user.ts+++ b/frontend/src/metabase-types/api/user.ts@@ -1,7 +1,9 @@import type { CollectionId } from "./collection";import type { DashboardId } from "./dashboard";+import type { DatabaseId } from "./database";import type { DependencyDiagnosticsUserParams } from "./dependencies";import type { PaginationRequest, PaginationResponse } from "./pagination";+import type { ConcreteTableId, SchemaName } from "./table";export type UserId = number;export type UserAttributeKey = string;@@ -194,6 +196,21 @@ export type UserKeyValue =namespace: "dependency_diagnostics";key: string;value: DependencyDiagnosticsUserParams;+ }+ | {+ namespace: "schema_viewer";+ key: "last_database";+ value: {+ databaseId: DatabaseId;+ schema?: SchemaName;+ };+ }+ | {+ namespace: "schema_viewer";+ key: `${DatabaseId}__${SchemaName}`;+ value: {+ table_ids: ConcreteTableId[];+ };};export type UserKeyValueKey = Pick<UserKeyValue, "namespace" | "key">;diff --git a/frontend/src/metabase/admin/tools/components/ToolsApp.tsx b/frontend/src/metabase/admin/tools/components/ToolsApp.tsxindex 39a3f1a116e..9ebd9bb4732 100644--- a/frontend/src/metabase/admin/tools/components/ToolsApp.tsx+++ b/frontend/src/metabase/admin/tools/components/ToolsApp.tsx@@ -30,7 +30,7 @@ export function ToolsApp({ location, children }: ToolsAppProps) {/><ToolsNavItemlabel={t`Tasks`}- path={Urls.adminToolsTasksBase()}+ path={Urls.adminToolsTasks()}icon="clipboard"location={location}/>diff --git a/frontend/src/metabase/api/table.ts b/frontend/src/metabase/api/table.tsindex 3f05b926b32..c1a5005f674 100644--- a/frontend/src/metabase/api/table.ts+++ b/frontend/src/metabase/api/table.ts@@ -98,6 +98,7 @@ export const tableApi = Api.injectEndpoints({tag("database"),tag("card"),tag("dataset"),+ listTag("erd"),]),}),updateTableList: builder.mutation<Table[], UpdateTableListRequest>({@@ -112,6 +113,7 @@ export const tableApi = Api.injectEndpoints({tag("database"),tag("card"),tag("dataset"),+ listTag("erd"),]),}),updateTableFieldsOrder: builder.mutation<@@ -130,6 +132,7 @@ export const tableApi = Api.injectEndpoints({listTag("field"),tag("card"),tag("dataset"),+ listTag("erd"),]),}),rescanTableFieldValues: builder.mutation<void, TableId>({@@ -152,6 +155,7 @@ export const tableApi = Api.injectEndpoints({listTag("field-values"),listTag("parameter-values"),tag("card"),+ listTag("erd"),]),}),discardTableFieldValues: builder.mutation<void, TableId>({@@ -178,6 +182,7 @@ export const tableApi = Api.injectEndpoints({idTag("table", tableId),listTag("field"),listTag("field-values"),+ listTag("erd"),]),}),replaceTableCsv: builder.mutation<@@ -196,6 +201,7 @@ export const tableApi = Api.injectEndpoints({idTag("table", tableId),listTag("field"),listTag("field-values"),+ listTag("erd"),]),}),diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.tsindex 5bdca66c3db..6e65ef072a1 100644--- a/frontend/src/metabase/api/tags/constants.ts+++ b/frontend/src/metabase/api/tags/constants.ts@@ -18,6 +18,7 @@ export const TAG_TYPES = ["dataset","document","embed-theme",+ "erd","external-transform","public-document","comment",diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsxindex 28c7ecaf65f..2a31f732583 100644--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPickerItemList.tsx@@ -282,7 +282,12 @@ function DatabaseItemList({}: {parent: MiniPickerDatabaseItem | MiniPickerSchemaItem;}) {- const { setPath, onChange, isHidden } = useMiniPickerContext();+ const { setPath, onChange, isHidden, models } = useMiniPickerContext();+ // Callers opt schemas in as a terminal pick by including "schema" in+ // `models`. Affects three things: schemas fire `onChange` instead of+ // `setPath`, single-schema DBs no longer auto-drill to tables, and the+ // schema row drops its folder chevron.+ const schemasArePickable = models.includes("schema");const { data: allSchemas, isLoading: isLoadingSchemas } =useListDatabaseSchemasQuery(parent.model === "database"@@ -290,13 +295,13 @@ function DatabaseItemList({: skipToken,);- const dbId = parent.model === "database" ? parent.id : parent.dbId!;+ const dbId = parent.model === "database" ? parent.id : parent.database_id!;const schemas = allSchemas?.filter((schema) => {return !isHidden({model: "schema",id: schema,- dbId,+ database_id: dbId,name: schema,});});@@ -304,7 +309,7 @@ function DatabaseItemList({const schemaName: SchemaName | null =parent.model === "schema"? String(parent.id)- : schemas?.length === 1+ : !schemasArePickable && schemas?.length === 1? schemas[0] // if there's one schema, go straight to tables: null;@@ -323,28 +328,36 @@ function DatabaseItemList({return <MiniPickerListLoader />;}- if (schemas?.length && schemas.length > 1 && parent.model === "database") {+ if (+ schemas?.length &&+ parent.model === "database" &&+ (schemas.length > 1 || schemasArePickable)+ ) {return (<ItemList>- {schemas.map((schema) => (- <MiniPickerItem- key={schema}- name={schema}- isFolder- model="schema"- onClick={() => {- setPath((prevPath) => [- ...prevPath,- {- model: "schema",- id: schema,- dbId,- name: schema,- },- ]);- }}- />- ))}+ {schemas.map((schema) => {+ const schemaItem: MiniPickerSchemaItem = {+ model: "schema",+ id: schema,+ database_id: dbId,+ name: schema,+ };+ return (+ <MiniPickerItem+ key={schema}+ name={schema}+ isFolder={!schemasArePickable}+ model="schema"+ onClick={() => {+ if (schemasArePickable) {+ onChange(schemaItem);+ } else {+ setPath((prevPath) => [...prevPath, schemaItem]);+ }+ }}+ />+ );+ })}</ItemList>);}@@ -592,6 +605,12 @@ const isMeasure = (return item.model === "measure";};+const isSchema = (+ item: MiniPickerPickableItem,+): item is MiniPickerSchemaItem => {+ return item.model === "schema";+};+const useLocationDetails = (item: MiniPickerPickableItem) => {const getIcon = useGetIcon();@@ -607,6 +626,14 @@ const useLocationDetails = (item: MiniPickerPickableItem) => {iconProps: { name: "table" as const },};}+ if (isSchema(item)) {+ // Schemas don't appear in search results (see SearchableMiniPickerItem)+ // so this branch is defensive; surface the parent database id at most.+ return {+ itemText: String(item.database_id),+ iconProps: { name: "database" as const },+ };+ }return {itemText: item?.collection?.name ?? t`Our analytics`,iconProps: getIcon({ ...item.collection, model: "collection" }),diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/types.ts b/frontend/src/metabase/common/components/Pickers/MiniPicker/types.tsindex 5fa39644b9e..6d983e4c642 100644--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/types.ts+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/types.ts@@ -34,7 +34,7 @@ export type MiniPickerPickableCollectionItem = MiniPickerCollectionItem & {export type MiniPickerSchemaItem = {model: "schema";id: SchemaName;- dbId: DatabaseId;+ database_id: DatabaseId;name: SchemaName;};@@ -87,11 +87,15 @@ export type MiniPickerFolderItem =| MiniPickerSchemaItem| MiniPickerCollectionFolderItem;-// this omits intermediate/folder types that cannot ultimately be picked+// this omits intermediate/folder types that cannot ultimately be picked.+// `MiniPickerSchemaItem` is included so callers that pass `models: ["schema"]`+// can terminate selection on a schema (schemas otherwise default to folder+// behaviour and only update the path).export type MiniPickerPickableItem =| MiniPickerPickableCollectionItem| MiniPickerTableItem- | MiniPickerMeasureItem;+ | MiniPickerMeasureItem+ | MiniPickerSchemaItem;// can't get schemas in search resultsexport type SearchableMiniPickerItem =diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.tsindex ab86119b2ae..3e4fe911019 100644--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts@@ -114,7 +114,14 @@ async function getTablePathFromValue(return [...(db ? [{ id: db.id, name: db.name, model: "database" as const }] : []),...(db && schema- ? [{ id: schema, name: schema, model: "schema" as const, dbId: db.id }]+ ? [+ {+ id: schema,+ name: schema,+ model: "schema" as const,+ database_id: db.id,+ },+ ]: []),];}@@ -247,13 +254,16 @@ export function getFolderAndHiddenFunctions(return false;}- if (- item.model === MiniPickerFolderModel.Database ||- item.model === MiniPickerFolderModel.Schema- ) {+ if (item.model === MiniPickerFolderModel.Database) {return true;}+ if (item.model === MiniPickerFolderModel.Schema) {+ // When the caller opts schemas into the pickable model set, schemas+ // become terminal and don't drill into tables.+ return !modelSet.has("schema");+ }+if (item.model !== MiniPickerFolderModel.Collection) {return false;}diff --git a/frontend/src/metabase/common/hooks/use-user-key-value.ts b/frontend/src/metabase/common/hooks/use-user-key-value.tsindex dece9f046ba..e076932eef7 100644--- a/frontend/src/metabase/common/hooks/use-user-key-value.ts+++ b/frontend/src/metabase/common/hooks/use-user-key-value.ts@@ -8,17 +8,58 @@ import {} from "metabase/api";import { useSelector } from "metabase/redux";import { getUser } from "metabase/selectors/user";-import type { UserKeyValue } from "metabase-types/api";+import type {+ UpdateUserKeyValueRequest,+ UserKeyValue,+} from "metabase-types/api";-export interface UseUserKeyValueParams<T extends UserKeyValue> {+type UserKeyValueNamespace<Namespace extends UserKeyValue["namespace"]> =+ Extract<UserKeyValue, { namespace: Namespace }>;++type ExactUserKeyValue<+ Namespace extends UserKeyValue["namespace"],+ Key extends string,+> = Extract<UserKeyValueNamespace<Namespace>, { key: Key }>;++type UserKeyValueFor<Params extends Pick<UserKeyValue, "namespace" | "key">> = [+ ExactUserKeyValue<Params["namespace"], Params["key"]>,+] extends [never]+ ? UserKeyValueNamespace<Params["namespace"]> extends infer NamespaceMatch+ ? NamespaceMatch extends UserKeyValue+ ? Params["key"] extends NamespaceMatch["key"]+ ? NamespaceMatch+ : never+ : never+ : never+ : ExactUserKeyValue<Params["namespace"], Params["key"]>;++export type UseUserKeyValueParams<+ Params extends Pick<UserKeyValue, "namespace" | "key"> = UserKeyValue,+> = {+ namespace: Params["namespace"];+ key: Params["key"];+ defaultValue?: UserKeyValueFor<Params>["value"];+ skip?: boolean;+};++type UseUserKeyValueImplementationParams<T extends UserKeyValue> = {namespace: T["namespace"];key: T["key"];defaultValue?: T["value"];skip?: boolean;-}+};export type UseUserKeyValueResult<T extends UserKeyValue> = {value: T["value"];+ /**+ * Like `value`, but reflects only the result for the current `(namespace,+ * key)` args. While a new subscription is settling after args change,+ * `value` "sticks" to the previous args' result (RTK Query's `data`+ * field), which can leak stale state into consumers that read it+ * synchronously during render. `currentValue` is `undefined` during that+ * transition window — use it when staleness across key changes matters.+ */+ currentValue: T["value"] | undefined;setValue: (value: T["value"]) => Promise<{ data?: unknown; error?: unknown }>;isLoading: boolean;isMutating: boolean;@@ -26,17 +67,27 @@ export type UseUserKeyValueResult<T extends UserKeyValue> = {clearValue: () => Promise<{ data?: unknown; error?: unknown }>;};+export function useUserKeyValue<+ Namespace extends UserKeyValue["namespace"],+ Key extends string,+>(params: {+ namespace: Namespace;+ key: Key;+ defaultValue?: UserKeyValueFor<{ namespace: Namespace; key: Key }>["value"];+ skip?: boolean;+}): UseUserKeyValueResult<UserKeyValueFor<{ namespace: Namespace; key: Key }>>;export function useUserKeyValue<T extends UserKeyValue>({namespace,key,defaultValue,skip = false,-}: UseUserKeyValueParams<T>): UseUserKeyValueResult<T> {+}: UseUserKeyValueImplementationParams<T>): UseUserKeyValueResult<T> {const user = useSelector(getUser) ?? null;const queryParams = user && !skip ? { namespace, key } : skipToken;const {data: valueFromQuery,+ currentData: currentValueFromQuery,isLoading: queryIsLoading,error: fetchError,} = useGetUserKeyValueQuery(queryParams);@@ -47,7 +98,18 @@ export function useUserKeyValue<T extends UserKeyValue>({if (!user) {return { error: "No user" };}- return await setMutation({ namespace, key, value });+ // The implementation signature uses `T extends UserKeyValue`, which+ // doesn't preserve the correlation between `namespace`, `key`, and+ // `value` across the union — TypeScript widens the constructed object+ // to a cross-product and rejects it against the per-variant+ // `UpdateUserKeyValueRequest`. The runtime call is correct because+ // the public overload signature constrains the inputs, so cast here+ // to bridge the body-level type loss.+ return await setMutation({+ namespace,+ key,+ value,+ } as UpdateUserKeyValueRequest);},[setMutation, namespace, key, user],);@@ -68,6 +130,7 @@ export function useUserKeyValue<T extends UserKeyValue>({// the request is in flight, which also falls back to `defaultValue`.)return {value: user ? (valueFromQuery ?? defaultValue) : defaultValue,+ currentValue: user ? currentValueFromQuery : undefined,setValue,clearValue,isLoading: user ? queryIsLoading : false,diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsxindex 26e2b5474bd..09990f2fa52 100644--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx@@ -101,6 +101,7 @@ function DataStudioNav({ isNavbarOpened, onNavbarToggle }: DataStudioNavProps) {const hasLibraryFeature = useHasTokenFeature("library");const hasDependenciesFeature = useHasTokenFeature("dependencies");+ const hasSchemaViewerFeature = useHasTokenFeature("schema-viewer");const hasRemoteSyncFeature = useHasTokenFeature("remote_sync");const hasTransformsFeature = useSelector(getTransformsFeatureAvailable);@@ -145,11 +146,12 @@ function DataStudioNav({ isNavbarOpened, onNavbarToggle }: DataStudioNavProps) {/>)}<DataStudioTab- label={t`Glossary`}- icon="glossary"- to={Urls.dataStudioGlossary()}- isSelected={currentTab === "glossary"}+ label={t`Schema viewer`}+ icon="network"+ to={Urls.dataStudioSchemaViewer()}+ isSelected={currentTab === "schema-viewer"}showLabel={isNavbarOpened}+ isGated={!hasSchemaViewerFeature}/><DataStudioTablabel={t`Dependency graph`}@@ -183,6 +185,13 @@ function DataStudioNav({ isNavbarOpened, onNavbarToggle }: DataStudioNavProps) {}/>)}+ <DataStudioTab+ label={t`Glossary`}+ icon="glossary"+ to={Urls.dataStudioGlossary()}+ isSelected={currentTab === "glossary"}+ showLabel={isNavbarOpened}+ /></Stack><Stack gap="0.75rem">{hasRemoteSyncFeature ? (diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/setup.tsx b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/setup.tsxindex 064158ce0af..403f3328149 100644--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/setup.tsx+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/tests/setup.tsx@@ -233,6 +233,7 @@ export const DEFAULT_EE_SETTINGS: Partial<SetupOpts> = {advanced_permissions: true,library: true,dependencies: true,+ "schema-viewer": true,workspaces: true,},};diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.tsindex 47fe45ef93c..e68872e116b 100644--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/utils.ts@@ -8,6 +8,7 @@ type TabName =| "runs"| "dependencies"| "dependency-diagnostics"+ | "schema-viewer"| "glossary"| "git-sync"| "workspaces";@@ -26,6 +27,8 @@ export const getCurrentTab = (pathname: string): TabName => {return "dependencies";case pathname.startsWith(Urls.dependencyDiagnostics()):return "dependency-diagnostics";+ case pathname.startsWith(Urls.dataStudioSchemaViewer()):+ return "schema-viewer";case pathname.startsWith(Urls.dataStudioLibrary()):return "library";case pathname.startsWith(Urls.transformRunList()):diff --git a/frontend/src/metabase/data-studio/data-model/components/TableSection/TableSection.tsx b/frontend/src/metabase/data-studio/data-model/components/TableSection/TableSection.tsxindex 06a607d5730..b29adb4df61 100644--- a/frontend/src/metabase/data-studio/data-model/components/TableSection/TableSection.tsx+++ b/frontend/src/metabase/data-studio/data-model/components/TableSection/TableSection.tsx@@ -326,6 +326,24 @@ const TableSectionBase = ({</Tooltip>)}+ <Tooltip label={t`Schema viewer`}>+ <Button+ component={ForwardRefLink}+ to={Urls.dataStudioSchemaViewer({+ databaseId: table.db_id,+ schema: table.schema,+ tableIds: [table.id],+ })}+ p="sm"+ leftSection={<Icon name="network" />}+ style={{+ flexGrow: 0,+ width: 40,+ }}+ aria-label={t`Schema viewer`}+ />+ </Tooltip>+<Box style={{ flexGrow: 0, width: 40 }}><TableLink table={table} /></Box>diff --git a/frontend/src/metabase/data-studio/routes.tsx b/frontend/src/metabase/data-studio/routes.tsxindex 218783d8258..077034cfd1d 100644--- a/frontend/src/metabase/data-studio/routes.tsx+++ b/frontend/src/metabase/data-studio/routes.tsx@@ -6,6 +6,7 @@ import {PLUGIN_DEPENDENCIES,PLUGIN_FEATURE_LEVEL_PERMISSIONS,PLUGIN_LIBRARY,+ PLUGIN_SCHEMA_VIEWER,PLUGIN_WORKSPACES,} from "metabase/plugins";import type { State } from "metabase/redux/store";@@ -26,6 +27,7 @@ import {DependenciesUpsellPage,DependencyDiagnosticsUpsellPage,LibraryUpsellPage,+ SchemaViewerUpsellPage,} from "./upsells/pages";export function getDataStudioRoutes(@@ -80,6 +82,13 @@ export function getDataStudioRoutes(component={DependencyDiagnosticsUpsellPage}/>)}+ {PLUGIN_SCHEMA_VIEWER.isEnabled ? (+ <Route path="schema-viewer">+ {PLUGIN_SCHEMA_VIEWER.getDataStudioSchemaViewerRoutes()}+ </Route>+ ) : (+ <Route path="schema-viewer" component={SchemaViewerUpsellPage} />+ )}<Route path="git-sync" component={GitSyncSectionLayout} /></Route></Route>diff --git a/frontend/src/metabase/data-studio/upsells/pages/SchemaViewerUpsellPage.tsx b/frontend/src/metabase/data-studio/upsells/pages/SchemaViewerUpsellPage.tsxnew file mode 100644index 00000000000..afed3f15e5c--- /dev/null+++ b/frontend/src/metabase/data-studio/upsells/pages/SchemaViewerUpsellPage.tsx@@ -0,0 +1,20 @@+import { t } from "ttag";++import { usePageTitle } from "metabase/hooks/use-page-title";++import { BaseUpsellPage } from "./BaseUpsellPage";++export function SchemaViewerUpsellPage() {+ usePageTitle(t`Schema viewer`);++ return (+ <BaseUpsellPage+ campaign="data-studio-schema-viewer"+ location="data-studio-schema-viewer-page"+ header={t`Schema viewer`}+ title={t`Visualize your database structure`}+ description={t`Explore tables and their relationships at a glance. Follow foreign keys, expand into related tables, and see how your schema fits together.`}+ image="app/assets/img/schema-viewer.svg"+ />+ );+}diff --git a/frontend/src/metabase/data-studio/upsells/pages/index.ts b/frontend/src/metabase/data-studio/upsells/pages/index.tsindex 4f91dd89c68..f09f4db63c3 100644--- a/frontend/src/metabase/data-studio/upsells/pages/index.ts+++ b/frontend/src/metabase/data-studio/upsells/pages/index.ts@@ -2,3 +2,4 @@ export { DependenciesUpsellPage } from "./DependenciesUpsellPage";export { DependencyDiagnosticsUpsellPage } from "./DependencyDiagnosticsUpsellPage";export { LibraryUpsellPage } from "./LibraryUpsellPage";export { RemoteSyncUpsellPage } from "./RemoteSyncUpsellPage";+export { SchemaViewerUpsellPage } from "./SchemaViewerUpsellPage";diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.tsindex ca3d6afafa9..71abfd942c7 100644--- a/frontend/src/metabase/plugins/index.ts+++ b/frontend/src/metabase/plugins/index.ts@@ -114,6 +114,7 @@ export {type SourceReplacementTriggeredFrom,} from "./oss/replacement";export { PLUGIN_RESOURCE_DOWNLOADS } from "./oss/resource-downloads";+export { PLUGIN_SCHEMA_VIEWER } from "./oss/schema-viewer";export {PLUGIN_SEMANTIC_SEARCH,type SearchSettingsWidgetProps,@@ -193,6 +194,7 @@ import { reinitialize as reinitializePermissions } from "./oss/permissions";import { reinitialize as reinitializeRemoteSync } from "./oss/remote-sync";import { reinitialize as reinitializeReplacement } from "./oss/replacement";import { reinitialize as reinitializeResourceDownloads } from "./oss/resource-downloads";+import { reinitialize as reinitializeSchemaViewer } from "./oss/schema-viewer";import { reinitialize as reinitializeSecurityCenter } from "./oss/security-center";import { reinitialize as reinitializeSemanticSearch } from "./oss/semantic-search";import { reinitialize as reinitializeSettings } from "./oss/settings";@@ -236,6 +238,7 @@ export function reinitialize() {reinitializeRemoteSync();reinitializeReplacement();reinitializeResourceDownloads();+ reinitializeSchemaViewer();reinitializeSecurityCenter();reinitializeSemanticSearch();reinitializeSettings();diff --git a/frontend/src/metabase/plugins/oss/schema-viewer.ts b/frontend/src/metabase/plugins/oss/schema-viewer.tsnew file mode 100644index 00000000000..b9b2eadf9e6--- /dev/null+++ b/frontend/src/metabase/plugins/oss/schema-viewer.ts@@ -0,0 +1,20 @@+import type { ReactNode } from "react";++type SchemaViewerPlugin = {+ isEnabled: boolean;+ getDataStudioSchemaViewerRoutes: () => ReactNode;+};++const getDefaultPluginSchemaViewer = (): SchemaViewerPlugin => ({+ isEnabled: false,+ getDataStudioSchemaViewerRoutes: () => null,+});++export const PLUGIN_SCHEMA_VIEWER = getDefaultPluginSchemaViewer();++/**+ * @internal Do not call directly. Use the main reinitialize function from metabase/plugins instead.+ */+export function reinitialize() {+ Object.assign(PLUGIN_SCHEMA_VIEWER, getDefaultPluginSchemaViewer());+}diff --git a/frontend/src/metabase/urls/admin.ts b/frontend/src/metabase/urls/admin.tsindex 87017236de1..8206efbf9af 100644--- a/frontend/src/metabase/urls/admin.ts+++ b/frontend/src/metabase/urls/admin.ts@@ -164,11 +164,11 @@ export function adminToolsHelp() {return "/admin/tools/help";}-export function adminToolsTasksBase() {+export function adminToolsTasks() {return "/admin/tools/tasks";}export function adminToolsTasksList() {- return `${adminToolsTasksBase()}/list`;+ return `${adminToolsTasks()}/list`;}export function adminToolsTaskDetails(taskId: number) {@@ -176,7 +176,7 @@ export function adminToolsTaskDetails(taskId: number) {}export function adminToolsTasksRuns() {- return `${adminToolsTasksBase()}/runs`;+ return `${adminToolsTasks()}/runs`;}export function adminToolsTaskRunDetails(runId: number) {diff --git a/frontend/src/metabase/urls/data-studio.ts b/frontend/src/metabase/urls/data-studio.tsindex 1f14b977fca..5376ff89630 100644--- a/frontend/src/metabase/urls/data-studio.ts+++ b/frontend/src/metabase/urls/data-studio.ts@@ -2,6 +2,7 @@ import type {CardId,CollectionId,DatabaseId,+ ErdParams,FieldId,MeasureId,NativeQuerySnippetId,@@ -270,6 +271,47 @@ export function dataStudioMetricHistory(cardId: CardId) {return `${dataStudioMetric(cardId)}/history`;}+type DataStudioSchemaViewerParams = {+ databaseId: DatabaseId;+ schema?: SchemaName;+ tableIds?: readonly TableId[];+};++export function getSchemaViewerParams({+ databaseId,+ schema,+ tableIds,+}: DataStudioSchemaViewerParams): ErdParams {+ const params: ErdParams = { "database-id": databaseId };+ if (schema != null) {+ params.schema = schema;+ }+ if (tableIds != null && tableIds.length > 0) {+ params["table-ids"] = [...tableIds];+ }+ return params;+}++export function dataStudioSchemaViewer(args?: DataStudioSchemaViewerParams) {+ const SCHEMA_VIEWER_BASE_URL = `${ROOT_URL}/schema-viewer`;+ if (!args) {+ return SCHEMA_VIEWER_BASE_URL;+ }++ const queryParams = getSchemaViewerParams(args);+ const params = new URLSearchParams();+ params.set("database-id", String(queryParams["database-id"]));+ if (queryParams.schema != null) {+ params.set("schema", queryParams.schema);+ }+ if (queryParams["table-ids"] != null) {+ for (const id of queryParams["table-ids"]) {+ params.append("table-ids", String(id));+ }+ }+ return `${SCHEMA_VIEWER_BASE_URL}?${params.toString()}`;+}+export function dataStudioGlossary() {return `${dataStudio()}/glossary`;}diff --git a/frontend/test/__support__/enterprise-typed.ts b/frontend/test/__support__/enterprise-typed.tsindex ea224ada53c..f5990abebf9 100644--- a/frontend/test/__support__/enterprise-typed.ts+++ b/frontend/test/__support__/enterprise-typed.ts@@ -21,6 +21,7 @@ export const ENTERPRISE_PLUGIN_NAME_MAPPING = {embedding: "metabase-enterprise/embedding",admin: "metabase-enterprise/admin",dependencies: "metabase-enterprise/dependencies",+ schema_viewer: "metabase-enterprise/schema_viewer",feature_level_permissions: "metabase-enterprise/feature_level_permissions",shared: "metabase-enterprise/shared",transforms: "metabase-enterprise/transforms",diff --git a/resources/frontend_client/app/assets/img/schema-viewer.svg b/resources/frontend_client/app/assets/img/schema-viewer.svgnew file mode 100644index 00000000000..630c26d4b6e--- /dev/null+++ b/resources/frontend_client/app/assets/img/schema-viewer.svg@@ -0,0 +1,47 @@+<svg width="400" height="400" viewBox="0 0 400 400" fill="none" xmlns="http://www.w3.org/2000/svg">+<rect width="400" height="400" fill="white"/>+<path d="M59 64C59 59.5817 62.5817 56 67 56H123C127.418 56 131 59.5817 131 64V102C131 106.418 127.418 110 123 110H67C62.5817 110 59 106.418 59 102V64Z" fill="white"/>+<path d="M130.375 64C130.375 59.9269 127.073 56.625 123 56.625H67C62.9269 56.625 59.625 59.9269 59.625 64V102C59.625 106.073 62.9269 109.375 67 109.375H123C127.073 109.375 130.375 106.073 130.375 102V64ZM131.625 102C131.625 106.763 127.763 110.625 123 110.625H67C62.2365 110.625 58.375 106.763 58.375 102V64C58.375 59.2365 62.2365 55.375 67 55.375H123C127.763 55.375 131.625 59.2365 131.625 64V102Z" fill="#509EE3"/>+<path d="M59 64C59 59.5817 62.5817 56 67 56H83V110H67C62.5817 110 59 106.418 59 102V64Z" fill="#0572D2" fill-opacity="0.07"/>+<path d="M83.625 55.375V110.625H67C62.2365 110.625 58.375 106.763 58.375 102V64C58.375 59.2365 62.2365 55.375 67 55.375H83.625ZM59.625 102C59.625 106.073 62.9269 109.375 67 109.375H82.375V56.625H67C62.9269 56.625 59.625 59.9269 59.625 64V102Z" fill="#509EE3"/>+<path opacity="0.25" d="M131 73.375V74.625H59V73.375H131Z" fill="#509EE3"/>+<path opacity="0.25" d="M131 91.375V92.625H59V91.375H131Z" fill="#509EE3"/>+<path d="M171 298C171 293.582 174.582 290 179 290H235C239.418 290 243 293.582 243 298V336C243 340.418 239.418 344 235 344H179C174.582 344 171 340.418 171 336V298Z" fill="white"/>+<path d="M242.375 298C242.375 293.927 239.073 290.625 235 290.625H179C174.927 290.625 171.625 293.927 171.625 298V336C171.625 340.073 174.927 343.375 179 343.375H235C239.073 343.375 242.375 340.073 242.375 336V298ZM243.625 336C243.625 340.763 239.763 344.625 235 344.625H179C174.237 344.625 170.375 340.763 170.375 336V298C170.375 293.237 174.237 289.375 179 289.375H235C239.763 289.375 243.625 293.237 243.625 298V336Z" fill="#509EE3"/>+<path d="M171 298C171 293.582 174.582 290 179 290H195V344H179C174.582 344 171 340.418 171 336V298Z" fill="#0572D2" fill-opacity="0.07"/>+<path d="M195.625 289.375V344.625H179C174.237 344.625 170.375 340.763 170.375 336V298C170.375 293.237 174.237 289.375 179 289.375H195.625ZM171.625 336C171.625 340.073 174.927 343.375 179 343.375H194.375V290.625H179C174.927 290.625 171.625 293.927 171.625 298V336Z" fill="#509EE3"/>+<path opacity="0.25" d="M243 307.375V308.625H171V307.375H243Z" fill="#509EE3"/>+<path opacity="0.25" d="M243 325.375V326.625H171V325.375H243Z" fill="#509EE3"/>+<path d="M273 182C273 177.582 276.582 174 281 174H337C341.418 174 345 177.582 345 182V220C345 224.418 341.418 228 337 228H281C276.582 228 273 224.418 273 220V182Z" fill="white"/>+<path d="M344.375 182C344.375 177.927 341.073 174.625 337 174.625H281C276.927 174.625 273.625 177.927 273.625 182V220C273.625 224.073 276.927 227.375 281 227.375H337C341.073 227.375 344.375 224.073 344.375 220V182ZM345.625 220C345.625 224.763 341.763 228.625 337 228.625H281C276.237 228.625 272.375 224.763 272.375 220V182C272.375 177.237 276.237 173.375 281 173.375H337C341.763 173.375 345.625 177.237 345.625 182V220Z" fill="#509EE3"/>+<path d="M273 182C273 177.582 276.582 174 281 174H297V228H281C276.582 228 273 224.418 273 220V182Z" fill="#0572D2" fill-opacity="0.07"/>+<path d="M297.625 173.375V228.625H281C276.237 228.625 272.375 224.763 272.375 220V182C272.375 177.237 276.237 173.375 281 173.375H297.625ZM273.625 220C273.625 224.073 276.927 227.375 281 227.375H296.375V174.625H281C276.927 174.625 273.625 177.927 273.625 182V220Z" fill="#509EE3"/>+<path opacity="0.25" d="M345 191.375V192.625H273V191.375H345Z" fill="#509EE3"/>+<path opacity="0.25" d="M345 209.375V210.625H273V209.375H345Z" fill="#509EE3"/>+<path d="M130.973 82.6992L130.972 82.0742L130.5 82.0742L130.5 83.3242L130.973 83.3242L130.973 82.6992ZM133.806 82.0732L132.861 82.0732L132.861 83.3232L133.806 83.3232L133.806 82.0732ZM136.639 82.0723L135.694 82.0732L135.694 83.3232L136.639 83.3223L136.639 82.0723ZM139.5 83.3223L139.5 82.0723L138.527 82.0723L138.527 82.6973L138.528 83.3223L139.5 83.3223ZM142.5 82.0723L141.5 82.0723L141.5 83.3223L142.5 83.3223L142.5 82.0723ZM145.5 82.0723L144.5 82.0723L144.5 83.3223L145.5 83.3223L145.5 82.0723ZM148 83.3223C148.169 83.3223 148.337 83.3247 148.505 83.3301L148.524 82.7061L148.545 82.0811C148.364 82.0752 148.182 82.0723 148 82.0723L147.5 82.0723L147.5 83.3223L148 83.3223ZM151.776 82.5029C151.425 82.4212 151.069 82.351 150.709 82.292L150.607 82.9082L150.507 83.5254C150.839 83.5799 151.168 83.6452 151.493 83.7207L151.776 82.5029ZM154.863 83.5508C154.534 83.4013 154.199 83.262 153.858 83.1338L153.417 84.3037C153.732 84.4223 154.042 84.5512 154.347 84.6895L154.605 84.1201L154.863 83.5508ZM157.685 85.1826C157.39 84.9714 157.088 84.7692 156.78 84.5771L156.45 85.1084L156.119 85.6387C156.404 85.8163 156.684 86.0028 156.956 86.1982L157.685 85.1826ZM160.134 87.332C159.886 87.0676 159.63 86.8113 159.365 86.5635L158.51 87.4756C158.755 87.705 158.992 87.9426 159.222 88.1875L160.134 87.332ZM162.119 89.917C161.927 89.6088 161.726 89.3069 161.515 89.0127L160.499 89.7412C160.694 90.0135 160.881 90.293 161.059 90.5781L161.589 90.2471L162.119 89.917ZM163.563 92.8389C163.435 92.4984 163.296 92.1634 163.146 91.834L162.577 92.0918L162.008 92.3506C162.146 92.6551 162.275 92.9646 162.394 93.2793L162.979 93.0596L163.563 92.8389ZM164.405 95.9883C164.346 95.6285 164.276 95.2726 164.194 94.9209L162.977 95.2041C163.052 95.529 163.117 95.8579 163.172 96.1904L163.789 96.0898L164.405 95.9883ZM164.625 98.6973C164.625 98.515 164.622 98.3332 164.616 98.1523L163.991 98.1729L163.367 98.1924C163.373 98.3599 163.375 98.5284 163.375 98.6973L163.375 99.1953L164.625 99.1953L164.625 98.6973ZM164.625 140.002L163.375 140.002L163.375 140.5L164.625 140.5L164.625 140.002ZM164.625 137.017L163.375 137.017L163.375 138.012L164.625 138.012L164.625 137.017ZM164.625 134.03L163.375 134.03L163.375 135.025L164.625 135.025L164.625 134.03ZM164.625 131.045L163.375 131.045L163.375 132.04L164.625 132.04L164.625 131.045ZM164.625 128.059L163.375 128.059L163.375 129.054L164.625 129.054L164.625 128.059ZM164.625 125.073L163.375 125.073L163.375 126.068L164.625 126.068L164.625 125.073ZM164.625 122.087L163.375 122.087L163.375 123.082L164.625 123.082L164.625 122.087ZM164.625 119.101L163.375 119.101L163.375 120.097L164.625 120.097L164.625 119.101ZM164.625 116.115L163.375 116.115L163.375 117.11L164.625 117.11L164.625 116.115ZM164.625 113.129L163.375 113.129L163.375 114.124L164.625 114.124L164.625 113.129ZM164.625 110.144L163.375 110.144L163.375 111.139L164.625 111.139L164.625 110.144ZM164.625 107.157L163.375 107.157L163.375 108.152L164.625 108.152L164.625 107.157ZM164.625 104.171L163.375 104.171L163.375 105.167L164.625 105.167L164.625 104.171ZM164.625 101.186L163.375 101.186L163.375 102.181L164.625 102.181L164.625 101.186Z" fill="#509EE3"/>+<path d="M171.036 317.426L171.5 317.426L171.5 316.176L171.036 316.176L171.036 317.426ZM168.25 317.427L169.179 317.427L169.179 316.177L168.25 316.177L168.25 317.427ZM165.464 316.802L165.465 317.427L166.393 317.427L166.393 316.177L165.464 316.177L165.464 316.802ZM162.679 317.427L163.607 317.427L163.607 316.177L162.679 316.177L162.679 317.427ZM159.893 317.427L160.821 317.427L160.821 316.177L159.893 316.177L159.893 317.427ZM157.107 317.428L158.036 317.428L158.036 316.178L157.107 316.178L157.107 317.428ZM154.321 317.428L155.25 317.428L155.25 316.178L154.321 316.178L154.321 317.428ZM151.5 316.178L151.5 317.428L152.465 317.428L152.464 316.803L152.464 316.178L151.5 316.178ZM148.5 317.428L149.5 317.428L149.5 316.178L148.5 316.178L148.5 317.428ZM145.5 317.428L146.5 317.428L146.5 316.178L145.5 316.178L145.5 317.428ZM143 316.178C142.831 316.178 142.663 316.175 142.495 316.17L142.476 316.794L142.455 317.419C142.636 317.425 142.818 317.428 143 317.428L143.5 317.428L143.5 316.178L143 316.178ZM139.224 316.997C139.575 317.079 139.931 317.149 140.291 317.208L140.393 316.592L140.493 315.975C140.161 315.92 139.832 315.855 139.507 315.779L139.224 316.997ZM136.137 315.949C136.466 316.099 136.801 316.238 137.142 316.366L137.583 315.196C137.268 315.078 136.958 314.949 136.653 314.811L136.395 315.38L136.137 315.949ZM133.315 314.317C133.61 314.529 133.912 314.731 134.22 314.923L134.55 314.392L134.881 313.861C134.596 313.684 134.316 313.497 134.044 313.302L133.315 314.317ZM130.866 312.168C131.114 312.432 131.37 312.689 131.635 312.937L132.49 312.024C132.245 311.795 132.008 311.557 131.778 311.312L130.866 312.168ZM128.881 309.583C129.073 309.891 129.274 310.193 129.485 310.487L130.501 309.759C130.306 309.487 130.119 309.207 129.941 308.922L129.411 309.253L128.881 309.583ZM127.437 306.661C127.565 307.002 127.704 307.337 127.854 307.666L128.423 307.408L128.992 307.149C128.854 306.845 128.725 306.535 128.606 306.221L128.021 306.44L127.437 306.661ZM126.595 303.512C126.654 303.871 126.724 304.227 126.806 304.579L128.023 304.296C127.948 303.971 127.883 303.642 127.828 303.31L127.211 303.41L126.595 303.512ZM126.375 300.803C126.375 300.985 126.378 301.167 126.384 301.348L127.009 301.327L127.633 301.308C127.627 301.14 127.625 300.972 127.625 300.803L127.625 300.305L126.375 300.305L126.375 300.803ZM126.375 259.498L127.625 259.498L127.625 259L126.375 259L126.375 259.498ZM126.375 262.483L127.625 262.483L127.625 261.488L126.375 261.488L126.375 262.483ZM126.375 265.47L127.625 265.47L127.625 264.475L126.375 264.475L126.375 265.47ZM126.375 268.455L127.625 268.455L127.625 267.46L126.375 267.46L126.375 268.455ZM126.375 271.441L127.625 271.441L127.625 270.446L126.375 270.446L126.375 271.441ZM126.375 274.427L127.625 274.427L127.625 273.432L126.375 273.432L126.375 274.427ZM126.375 277.413L127.625 277.413L127.625 276.418L126.375 276.418L126.375 277.413ZM126.375 280.399L127.625 280.399L127.625 279.403L126.375 279.403L126.375 280.399ZM126.375 283.385L127.625 283.385L127.625 282.39L126.375 282.39L126.375 283.385ZM126.375 286.371L127.625 286.371L127.625 285.376L126.375 285.376L126.375 286.371ZM126.375 289.356L127.625 289.356L127.625 288.361L126.375 288.361L126.375 289.356ZM126.375 292.343L127.625 292.343L127.625 291.348L126.375 291.348L126.375 292.343ZM126.375 295.329L127.625 295.329L127.625 294.333L126.375 294.333L126.375 295.329ZM126.375 298.314L127.625 298.314L127.625 297.319L126.375 297.319L126.375 298.314Z" fill="#509EE3"/>+<path d="M243.509 200.002L243.508 199.377L243 199.377L243 200.627L243.509 200.627L243.509 200.002ZM246.559 199.377L245.542 199.377L245.542 200.627L246.559 200.627L246.559 199.377ZM249.608 199.377L248.592 199.377L248.592 200.627L249.608 200.627L249.608 199.377ZM252.658 199.376L251.642 199.377L251.642 200.627L252.658 200.626L252.658 199.376ZM255.708 199.376L254.691 199.376L254.691 200.626L255.708 200.626L255.708 199.376ZM258.759 200.001L258.758 199.376L257.741 199.376L257.741 200.001L257.742 200.626L258.759 200.626L258.759 200.001ZM261.809 199.376L260.792 199.376L260.792 200.626L261.809 200.626L261.809 199.376ZM264.858 199.376L263.842 199.376L263.842 200.626L264.858 200.626L264.858 199.376ZM267.908 199.376L266.892 199.376L266.892 200.626L267.908 200.626L267.908 199.376ZM270.958 199.375L269.941 199.375L269.941 200.625L270.958 200.625L270.958 199.375ZM273.5 199.375L272.991 199.375L272.991 200.625L273.5 200.625L273.5 199.375Z" fill="#509EE3"/>+<path d="M83 150C83 144.477 87.4772 140 93 140H233C238.523 140 243 144.477 243 150V250C243 255.523 238.523 260 233 260H93C87.4772 260 83 255.523 83 250V150Z" fill="white"/>+<path d="M242.375 150C242.375 144.822 238.178 140.625 233 140.625H93C87.8223 140.625 83.625 144.822 83.625 150V250C83.625 255.178 87.8223 259.375 93 259.375H233C238.178 259.375 242.375 255.178 242.375 250V150ZM243.625 250C243.625 255.868 238.868 260.625 233 260.625H93C87.132 260.625 82.375 255.868 82.375 250V150C82.375 144.132 87.132 139.375 93 139.375H233C238.868 139.375 243.625 144.132 243.625 150V250Z" fill="#509EE3"/>+<path d="M98 224H112.5V245H98V224Z" fill="#CBE1F6"/>+<path d="M114.5 218H129V245H114.5V218Z" fill="#CBE1F6"/>+<path d="M131 207H145.5V245H131V207Z" fill="#CBE1F6"/>+<path d="M147.5 219H162V245H147.5V219Z" fill="#CBE1F6"/>+<path d="M164 203H178.5V245H164V203Z" fill="#CBE1F6"/>+<path d="M180.5 188H195V245H180.5V188Z" fill="#CBE1F6"/>+<path d="M197 203H211.5V245H197V203Z" fill="#CBE1F6"/>+<path d="M213.5 171H228V245H213.5V171Z" fill="#CBE1F6"/>+<path opacity="0.5" d="M83 155.375L243 155.375L243 156.625L83 156.625L83 155.375Z" fill="#509EE3"/>+<path d="M133.5 82.5C133.5 83.8807 132.381 85 131 85C129.619 85 128.5 83.8807 128.5 82.5C128.5 81.1193 129.619 80 131 80C132.381 80 133.5 81.1193 133.5 82.5Z" fill="white"/>+<path d="M132.25 82.5C132.25 81.8096 131.69 81.25 131 81.25C130.31 81.25 129.75 81.8096 129.75 82.5C129.75 83.1904 130.31 83.75 131 83.75V85C129.619 85 128.5 83.8807 128.5 82.5C128.5 81.1193 129.619 80 131 80C132.381 80 133.5 81.1193 133.5 82.5C133.5 83.8807 132.381 85 131 85V83.75C131.69 83.75 132.25 83.1904 132.25 82.5Z" fill="#509EE3"/>+<path d="M166.5 140C166.5 141.381 165.381 142.5 164 142.5C162.619 142.5 161.5 141.381 161.5 140C161.5 138.619 162.619 137.5 164 137.5C165.381 137.5 166.5 138.619 166.5 140Z" fill="white"/>+<path d="M165.25 140C165.25 139.31 164.69 138.75 164 138.75C163.31 138.75 162.75 139.31 162.75 140C162.75 140.69 163.31 141.25 164 141.25V142.5C162.619 142.5 161.5 141.381 161.5 140C161.5 138.619 162.619 137.5 164 137.5C165.381 137.5 166.5 138.619 166.5 140C166.5 141.381 165.381 142.5 164 142.5V141.25C164.69 141.25 165.25 140.69 165.25 140Z" fill="#509EE3"/>+<path d="M129.5 260C129.5 261.381 128.381 262.5 127 262.5C125.619 262.5 124.5 261.381 124.5 260C124.5 258.619 125.619 257.5 127 257.5C128.381 257.5 129.5 258.619 129.5 260Z" fill="white"/>+<path d="M128.25 260C128.25 259.31 127.69 258.75 127 258.75C126.31 258.75 125.75 259.31 125.75 260C125.75 260.69 126.31 261.25 127 261.25V262.5C125.619 262.5 124.5 261.381 124.5 260C124.5 258.619 125.619 257.5 127 257.5C128.381 257.5 129.5 258.619 129.5 260C129.5 261.381 128.381 262.5 127 262.5V261.25C127.69 261.25 128.25 260.69 128.25 260Z" fill="#509EE3"/>+<path d="M173.5 316.5C173.5 317.881 172.381 319 171 319C169.619 319 168.5 317.881 168.5 316.5C168.5 315.119 169.619 314 171 314C172.381 314 173.5 315.119 173.5 316.5Z" fill="white"/>+<path d="M172.25 316.5C172.25 315.81 171.69 315.25 171 315.25C170.31 315.25 169.75 315.81 169.75 316.5C169.75 317.19 170.31 317.75 171 317.75V319C169.619 319 168.5 317.881 168.5 316.5C168.5 315.119 169.619 314 171 314C172.381 314 173.5 315.119 173.5 316.5C173.5 317.881 172.381 319 171 319V317.75C171.69 317.75 172.25 317.19 172.25 316.5Z" fill="#509EE3"/>+<path d="M245.5 200C245.5 201.381 244.381 202.5 243 202.5C241.619 202.5 240.5 201.381 240.5 200C240.5 198.619 241.619 197.5 243 197.5C244.381 197.5 245.5 198.619 245.5 200Z" fill="white"/>+<path d="M244.25 200C244.25 199.31 243.69 198.75 243 198.75C242.31 198.75 241.75 199.31 241.75 200C241.75 200.69 242.31 201.25 243 201.25V202.5C241.619 202.5 240.5 201.381 240.5 200C240.5 198.619 241.619 197.5 243 197.5C244.381 197.5 245.5 198.619 245.5 200C245.5 201.381 244.381 202.5 243 202.5V201.25C243.69 201.25 244.25 200.69 244.25 200Z" fill="#509EE3"/>+<path d="M275.5 200C275.5 201.381 274.381 202.5 273 202.5C271.619 202.5 270.5 201.381 270.5 200C270.5 198.619 271.619 197.5 273 197.5C274.381 197.5 275.5 198.619 275.5 200Z" fill="white"/>+<path d="M274.25 200C274.25 199.31 273.69 198.75 273 198.75C272.31 198.75 271.75 199.31 271.75 200C271.75 200.69 272.31 201.25 273 201.25V202.5C271.619 202.5 270.5 201.381 270.5 200C270.5 198.619 271.619 197.5 273 197.5C274.381 197.5 275.5 198.619 275.5 200C275.5 201.381 274.381 202.5 273 202.5V201.25C273.69 201.25 274.25 200.69 274.25 200Z" fill="#509EE3"/>+</svg>diff --git a/resources/user_key_value_types/schema_viewer.edn b/resources/user_key_value_types/schema_viewer.ednnew file mode 100644index 00000000000..d03543f7358--- /dev/null+++ b/resources/user_key_value_types/schema_viewer.edn@@ -0,0 +1,9 @@+[:map+ [:value [:or+ ;; Per-database/schema preferences (key = "databaseId:schema")+ [:map+ [:table_ids {:optional true} [:sequential :int]]]+ ;; Last opened database (key = "last_database")+ [:map+ [:databaseId :int]+ [:schema {:optional true} :string]]]]]diff --git a/src/metabase/analytics/stats.clj b/src/metabase/analytics/stats.cljindex da701d63329..30b6030ff91 100644--- a/src/metabase/analytics/stats.clj+++ b/src/metabase/analytics/stats.clj@@ -936,6 +936,9 @@{:name :dependencies:available (premium-features/enable-dependencies?):enabled (premium-features/enable-dependencies?)}+ {:name :schema-viewer+ :available (premium-features/enable-schema-viewer?)+ :enabled (premium-features/enable-schema-viewer?)}{:name :support-users:available (premium-features/enable-support-users?):enabled (premium-features/enable-support-users?)}diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.cljindex 086d6ecb8e1..c76a3b9ea66 100644--- a/src/metabase/premium_features/core.clj+++ b/src/metabase/premium_features/core.clj@@ -62,6 +62,7 @@enable-metabase-ai-managed?enable-metabot-v3?enable-dependencies?+ enable-schema-viewer?enable-email-allow-list?enable-email-restrict-recipients?enable-embedding-sdk-origins?diff --git a/src/metabase/premium_features/settings.clj b/src/metabase/premium_features/settings.cljindex b697c8a8b1a..19ff2ed0b3f 100644--- a/src/metabase/premium_features/settings.clj+++ b/src/metabase/premium_features/settings.clj@@ -363,6 +363,10 @@"Should we enable AI controls (metabot permissions, scope management)?":ai-controls)+(define-premium-feature ^{:added "0.62.0"} enable-schema-viewer?+ "Should we allow users to view database schemas as ER diagrams?"+ :schema-viewer)+(define-premium-feature enable-workspaces?"Should we allow users to manage workspaces?":workspaces)@@ -387,6 +391,7 @@:database_routing (enable-database-routing?):library (enable-library?):dependencies (enable-dependencies?)+ :schema-viewer (enable-schema-viewer?):development_mode (development-mode?):disable_password_login (can-disable-password-login?):email_allow_list (enable-email-allow-list?)diff --git a/src/metabase/warehouses_rest/api.clj b/src/metabase/warehouses_rest/api.cljindex 865b6692755..2011c78e4b5 100644--- a/src/metabase/warehouses_rest/api.clj+++ b/src/metabase/warehouses_rest/api.clj@@ -50,6 +50,11 @@(set! *warn-on-reflection* true)+;; Forward declaration so `add-schemas` (near the top-of-file helpers) can+;; reuse the same per-schema permission check used by `/api/database/:id/schemas`+;; lower in the file.+(declare can-read-schema?)+(def DBEngineString"Schema for a valid database engine name, e.g. `h2` or `postgres`."(mu/with-api-error-message@@ -79,6 +84,37 @@(for [db dbs](assoc db :tables (get db-id->tables (:id db) [])))))+(defn- add-schemas+ "Hydrate a `:schemas` field on each database with the list of schemas that+ have visible tables and that the current user can read — the same filtering+ rules the single-DB `/api/database/:id/schemas` endpoint applies. One SQL+ query covers the whole list so this is cheaper than the N round-trips a+ client would otherwise make to populate a database-picker dropdown."+ [dbs]+ (if (empty? dbs)+ dbs+ (let [db-ids (map :id dbs)+ rows (t2/query {:select-distinct [:db_id :schema]+ :from [(t2/table-name :model/Table)]+ :where [:and+ [:in :db_id db-ids]+ [:= :active true]+ [:= :visibility_type nil]]})+ schemas-by-db (reduce+ (fn [m {:keys [db_id schema]}]+ (update m db_id (fnil conj []) schema))+ {} rows)]+ (for [db dbs]+ (let [db-id (:id db)+ raw-schemas (get schemas-by-db db-id [])+ readable (->> raw-schemas+ (filter (partial can-read-schema? db-id))+ (map #(if (nil? %) "" %))+ distinct+ sort+ vec)]+ (assoc db :schemas readable))))))+(mu/defn- add-native-perms-info :- [:maybe[:sequential[:map@@ -279,6 +315,7 @@(defn- dbs-list[& {:keys [include-tables?+ include-schemas?include-saved-questions-db?include-saved-questions-tables?include-editable-data-model?@@ -312,6 +349,7 @@:where where-clause})](cond-> (-> dbs add-native-perms-info add-transforms-perms-info)include-tables? (add-tables :can-query? can-query? :can-write-metadata? can-write-metadata?)+ include-schemas? add-schemascan-query? (#(filter mi/can-query? %))true add-can-upload-to-dbstrue (t2/hydrate :router_user_attribute)@@ -334,6 +372,10 @@* `include=tables` means we should hydrate the Tables belonging to each DB. Default: `false`.+ * `include=schemas` hydrates a `:schemas` list on each DB (only schemas with visible+ tables the current user can read), matching the per-DB `/api/database/:id/schemas`+ response. Lets clients avoid N round-trips when populating a database/schema picker.+* `saved` means we should include the saved questions virtual database. Default: `false`.* `include_editable_data_model` will only include DBs for which the current user has data model editing@@ -359,8 +401,8 @@router_database_id can-query can-write-metadata]}:- [:map[:include {:optional true} (mu/with-api-error-message- [:maybe [:= "tables"]]- (deferred-tru "include must be either empty or the value ''tables''"))]+ [:maybe [:enum "tables" "schemas"]]+ (deferred-tru "include must be either empty, ''tables'', or ''schemas''"))][:include_analytics {:default false} [:maybe :boolean]][:saved {:default false} [:maybe :boolean]][:include_editable_data_model {:default false} [:maybe :boolean]]@@ -370,6 +412,7 @@[:can-query {:optional true} [:maybe :boolean]][:can-write-metadata {:optional true} [:maybe :boolean]]]](let [include-tables? (= include "tables")+ include-schemas? (= include "schemas")include-saved-questions-tables? (and saved include-tables?)only-editable? (or include_only_uploadable exclude_uneditable_details)has-table-metadata-perms? (fn [{db-id :id}]@@ -378,6 +421,7 @@:perms/manage-table-metadatadb-id)))db-list-res (cond->> (or (dbs-list :include-tables? include-tables?+ :include-schemas? include-schemas?:include-saved-questions-db? saved:include-saved-questions-tables? include-saved-questions-tables?:include-editable-data-model? include_editable_data_model