import { act, fireEvent, render, screen, within } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { DatabaseView } from "./DatabaseView"; import { executeAction } from "@/platform/actions"; import { setContext } from "@/platform/context"; import { registerDatabaseTreeActions } from "./treeActions"; import { schemasKey, tablesKey, useDatabase } from "./store"; import { databaseKey, schemaNodeKey, treeIdentifier } from "./model"; import { tableInput } from "./tableInput"; import { useEditorRegistry } from "@/editor/api"; import { provideEditorService, provideToolWindowService, type EditorInput } from "@/workbench/contributions"; vi.mock("@tanstack/react-virtual", () => ({ useVirtualizer: ({ count }: { count: number }) => ({ getTotalSize: () => count * 24, getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })), scrollToIndex: () => {}, measure: () => {}, }), })); let dispose: () => void; beforeEach(() => { localStorage.removeItem("openidea.database.viewOptions"); setContext("projectOpen", true); dispose = registerDatabaseTreeActions(); useDatabase.setState({ loaded: true, foldersLoaded: true, folders: [], sources: [{ id: "pg", name: "PostgreSQL", driver: "postgres", options: { singleDatabase: true } }], schemas: { pg: { status: "ok", value: ["public"] } }, tables: { [tablesKey("pg", "public")]: { status: "ok", value: [] } }, objects: { [tablesKey("pg", "public")]: { routines: [ { name: "calculate", kind: "function", arguments: "integer", returns: "integer" }, { name: "calculate", kind: "function", arguments: "text", returns: "text" }, { name: "refresh_data", kind: "procedure", arguments: "", returns: null }, ], packages: [], sequences: [], }, }, separateProceduresAndFunctions: false, showTableComments: true, treeExpanded: new Set(["pg", "pg/public", "pg/public/routines"]), }); }); describe("data source folders", () => { it("lists grouped sources under their folder and leaves ungrouped sources at the root", () => { useDatabase.setState({ sources: [ { id: "pg", name: "PostgreSQL", driver: "postgres" }, { id: "lite", name: "SQLite", driver: "sqlite" }, ], folders: [{ id: "prod", name: "Production", order: 0, sources: ["pg"] }], treeExpanded: new Set(["source-folder:prod"]), }); render(); const tree = within(screen.getByRole("tree", { name: "Data sources" })); const folder = tree.getByText("Production").closest('[role="treeitem"]')!; expect(folder).toHaveAttribute("aria-expanded", "true"); expect(tree.getByText("PostgreSQL").closest('[role="treeitem"]')).toHaveAttribute("aria-level", "2"); expect(tree.getByText("SQLite").closest('[role="treeitem"]')).toHaveAttribute("aria-level", "1"); }); }); afterEach(() => dispose()); describe("routine grouping", () => { it("keeps an existing expanded routines folder and both overloads by default", () => { render(); const tree = within(screen.getByRole("tree", { name: "Data sources" })); expect(tree.getByText("routines").closest('[role="treeitem"]')).toHaveAttribute("aria-expanded", "true"); expect(tree.getAllByText("calculate")).toHaveLength(2); expect(tree.getByText("refresh_data")).toBeInTheDocument(); expect(tree.queryByText("procedures")).toBeNull(); expect(tree.queryByText("functions")).toBeNull(); fireEvent.mouseDown(tree.getAllByText("calculate")[1]!, { button: 0 }); expect(useDatabase.getState().selectedNode?.key).toBe("pg/public/routines/calculate(text)"); }); it("toggles through the action, persists the option, and restores the old expansion", async () => { expect(useDatabase.getInitialState().separateProceduresAndFunctions).toBe(false); render(); const tree = within(screen.getByRole("tree", { name: "Data sources" })); await act(() => executeAction("db.separateProceduresAndFunctions")); expect(JSON.parse(localStorage.getItem("openidea.database.viewOptions")!)).toEqual({ separateProceduresAndFunctions: true, showTableComments: true, }); expect(tree.queryByText("routines")).toBeNull(); const procedures = tree.getByText("procedures").closest('[role="treeitem"]')!; const functions = tree.getByText("functions").closest('[role="treeitem"]')!; expect(within(procedures as HTMLElement).getByText("1")).toBeInTheDocument(); expect(within(functions as HTMLElement).getByText("2")).toBeInTheDocument(); fireEvent.mouseDown(functions.querySelector("[data-tree-toggle]")!, { button: 0 }); expect(tree.getAllByText("calculate")).toHaveLength(2); fireEvent.mouseDown(tree.getAllByText("calculate")[1]!, { button: 0 }); expect(useDatabase.getState().selectedNode?.key).toBe("pg/public/functions/calculate(text)"); await act(() => executeAction("db.separateProceduresAndFunctions")); expect(tree.getByText("routines").closest('[role="treeitem"]')).toHaveAttribute("aria-expanded", "true"); expect(tree.getAllByText("calculate")).toHaveLength(2); expect(tree.getByText("refresh_data")).toBeInTheDocument(); expect(JSON.parse(localStorage.getItem("openidea.database.viewOptions")!)).toEqual({ separateProceduresAndFunctions: false, showTableComments: true, }); }); it.each([false, true])("applies the object filter before grouping (separate: %s)", (separate) => { const source = useDatabase.getState().sources[0]!; useDatabase.setState({ separateProceduresAndFunctions: separate, sources: [{ ...source, introspection: { objectFilter: "calculate" } }], treeExpanded: new Set(["pg", "pg/public", "pg/public/routines", "pg/public/functions"]), }); render(); const tree = within(screen.getByRole("tree", { name: "Data sources" })); expect(tree.queryByText("procedures")).toBeNull(); expect(tree.queryByText("refresh_data")).toBeNull(); expect(tree.getAllByText("calculate")).toHaveLength(2); const folder = tree.getByText(separate ? "functions" : "routines").closest('[role="treeitem"]')!; expect(within(folder as HTMLElement).getByText("2")).toBeInTheDocument(); }); }); describe("table comments", () => { it("shows a table's comment after its name and hides it through the view option", async () => { useDatabase.setState({ tables: { [tablesKey("pg", "public")]: { status: "ok", value: [{ name: "orders", kind: "table", comment: "Customer orders" }], }, }, treeExpanded: new Set(["pg", "pg/public", "pg/public/tables"]), }); render(); const tree = within(screen.getByRole("tree", { name: "Data sources" })); expect(tree.getByText("Customer orders")).toBeInTheDocument(); expect(tree.getByText("orders").closest('[role="treeitem"]')).toHaveAttribute("title", "Customer orders"); await act(() => executeAction("db.showTableComments")); expect(tree.queryByText("Customer orders")).toBeNull(); expect(tree.getByText("orders").closest('[role="treeitem"]')).not.toHaveAttribute("title"); expect(JSON.parse(localStorage.getItem("openidea.database.viewOptions")!)).toEqual({ separateProceduresAndFunctions: false, showTableComments: false, }); }); }); describe("Select Opened File", () => { const nextFrame = () => act(() => new Promise((resolve) => requestAnimationFrame(() => resolve()))); let active: EditorInput | null = null; const show = vi.fn(); beforeEach(() => { provideEditorService({ activeInput: () => active } as never); provideToolWindowService({ show } as never); useDatabase.setState({ tables: { [tablesKey("pg", "public")]: { status: "ok", value: [ { name: "people", kind: "table" }, { name: "adults", kind: "view" }, ], }, }, schemas: { pg: { status: "ok", value: ["public", "audit"] } }, treeExpanded: new Set(), }); }); afterEach(() => { active = null; useEditorRegistry.setState({ active: null }); }); it("selects the active table editor's view in the views folder", async () => { render(); active = tableInput("pg", "public", "adults"); await act(() => executeAction("db.selectOpened")); await nextFrame(); expect(useDatabase.getState().selectedNode?.key).toBe("pg/public/views/adults"); expect(show).toHaveBeenCalledWith("database"); expect(document.activeElement).toBe(screen.getByRole("tree", { name: "Data sources" })); }); it("selects the nearest shown ancestor of a dropped table, and a console's schema", async () => { render(); active = tableInput("pg", "public", "dropped"); await act(() => executeAction("db.selectOpened")); await nextFrame(); expect(useDatabase.getState().selectedNode?.key).toBe("pg/public/tables"); const path = "/project/audit.sql"; useDatabase.setState({ consoles: { [path]: "pg" }, consoleSchemas: { [path]: "audit" } }); active = { kind: "file", key: path, path }; useEditorRegistry.setState({ active: { ctx: { path, language: "sql" } } as never }); await act(() => executeAction("db.selectOpened")); await nextFrame(); expect(useDatabase.getState().selectedNode?.key).toBe("pg/audit"); }); }); it("opens and reveals distinct DuckDB tables when the catalog is their only difference", async () => { const id = "duck"; const schema = "main"; const table = 'items/"quoted'; const catalogs = ["memory", "other.db:archive/one"]; const schemas = Object.fromEntries( catalogs.map((catalog) => [schemasKey(id, catalog), { status: "ok" as const, value: [schema] }]), ); const tables = Object.fromEntries( catalogs.map((catalog) => [ tablesKey(id, schema, catalog), { status: "ok" as const, value: [{ name: table, kind: "table" as const }] }, ]), ); const openInput = vi.fn(); let active: EditorInput | null = null; provideEditorService({ openInput, activeInput: () => active } as never); provideToolWindowService({ show: vi.fn() } as never); useDatabase.setState({ sources: [{ id, name: "DuckDB", driver: "jdbc", vendor: "duckdb" }], databases: { duck: { status: "ok", value: { current: "memory", names: catalogs } } }, schemas, tables, details: {}, objects: {}, treeExpanded: new Set([ id, ...catalogs.flatMap((catalog) => { const key = schemaNodeKey(id, schema, catalog); return [databaseKey(id, catalog, true), key, `${key}/tables`]; }), ]), }); render(); const tree = within(screen.getByRole("tree", { name: "Data sources" })); const entries = tree.getAllByText(table); expect(entries).toHaveLength(2); const first = tableInput(id, schema, table, catalogs[0]); active = tableInput(id, schema, table, catalogs[1]); fireEvent.doubleClick(entries[0]!); expect(openInput).toHaveBeenNthCalledWith(1, first, { focus: true }); fireEvent.mouseDown(entries[1]!, { button: 0 }); await act(() => executeAction("db.editData")); expect(openInput).toHaveBeenNthCalledWith(2, active, { focus: true }); expect(first.key).not.toBe(active.key); await act(() => executeAction("db.selectOpened")); await act(() => new Promise((resolve) => requestAnimationFrame(() => resolve()))); expect(useDatabase.getState().selectedNode?.key).toBe( `${schemaNodeKey(id, schema, catalogs[1])}/tables/${treeIdentifier(table, catalogs[1])}`, ); }); describe("Expand All", () => { it("opens every loaded node and leaves unloaded ones closed", async () => { useDatabase.setState({ sources: [ { id: "pg", name: "PostgreSQL", driver: "postgres", options: { singleDatabase: true } }, { id: "lite", name: "SQLite", driver: "sqlite" }, ], tables: { [tablesKey("pg", "public")]: { status: "ok", value: [{ name: "users", kind: "table" }] } }, treeExpanded: new Set(), }); render(); await act(() => executeAction("db.expandAll")); expect([...useDatabase.getState().treeExpanded].sort()).toEqual([ "pg", "pg/public", "pg/public/routines", "pg/public/tables", ]); const tree = within(screen.getByRole("tree", { name: "Data sources" })); expect(tree.getByText("refresh_data")).toBeInTheDocument(); // Its columns aren't loaded, and neither is the SQLite source: Expand All loads nothing. expect(tree.getByText("users").closest('[role="treeitem"]')).toHaveAttribute("aria-expanded", "false"); expect(tree.getByText("SQLite").closest('[role="treeitem"]')).toHaveAttribute("aria-expanded", "false"); }); }); describe("data source colour", () => { it("tints the whole tree row of the source and of every node under it", () => { useDatabase.setState({ sources: [ { id: "pg", name: "PostgreSQL", driver: "postgres", color: "red", options: { singleDatabase: true } }, { id: "lite", name: "SQLite", driver: "sqlite" }, ], }); render(); const tree = within(screen.getByRole("tree", { name: "Data sources" })); const tint = (name: string) => tree.getByText(name).closest('[role="treeitem"]')!.style.getPropertyValue("--row-tint"); for (const name of ["PostgreSQL", "public", "routines", "refresh_data"]) expect(tint(name)).toBe("var(--db-color-red)"); expect(tint("SQLite")).toBe(""); }); }); describe("multi-selection", () => { it("keeps every selected node in tree order, not only the lead, for Show Diagram", () => { useDatabase.setState({ tables: { [tablesKey("pg", "public")]: { status: "ok", value: ["users", "orders", "audit"].map((name) => ({ name, kind: "table" as const })), }, }, treeExpanded: new Set(["pg", "pg/public", "pg/public/tables"]), }); render(); const tree = within(screen.getByRole("tree", { name: "Data sources" })); const keys = () => useDatabase.getState().selectedNodes.map((n) => n.key); const click = (name: string, init: MouseEventInit = {}) => fireEvent.mouseDown(tree.getByText(name), { button: 0, ...init }); click("audit"); click("users", { metaKey: true }); expect(keys()).toEqual(["pg/public/tables/users", "pg/public/tables/audit"]); // ⌘-click on a selected row deselects it, yet it becomes the lead. click("users", { metaKey: true }); expect(keys()).toEqual(["pg/public/tables/audit"]); expect(useDatabase.getState().selectedNode?.key).toBe("pg/public/tables/users"); click("audit", { shiftKey: true }); expect(keys()).toEqual(["pg/public/tables/users", "pg/public/tables/orders", "pg/public/tables/audit"]); click("public"); expect(keys()).toEqual(["pg/public"]); }); });