diff --git a/src/features/database/TableEditor.tsx b/src/features/database/TableEditor.tsx index 701b1eb07..2f8e2019f 100644 --- a/src/features/database/TableEditor.tsx +++ b/src/features/database/TableEditor.tsx @@ -33,7 +33,7 @@ import { type Cell, type PendingEdits, } from "./model"; -import { openDialog, openDdl, sourceById, withConnection } from "./store"; +import { openDialog, openDdl, prefetchDdl, sourceById, withConnection } from "./store"; import type { TableRef } from "./tableInput"; import styles from "./Database.module.css"; import { registerTableEditor, tableEditorChanged, type TableEditorHandle } from "./tableEditorFocus"; @@ -122,6 +122,7 @@ export function TableEditor({ input }: { input: EditorInput }) { useEffect(() => { const id: RequestId = nextRequestId(); let done = false; + prefetchDdl(ref.id, ref.schema, ref.table, ref.catalog); void (async () => { try { const p = await withConnection(ref.id, () => diff --git a/src/features/database/ddlFile.test.ts b/src/features/database/ddlFile.test.ts index 8f8eaf14d..dd381efec 100644 --- a/src/features/database/ddlFile.test.ts +++ b/src/features/database/ddlFile.test.ts @@ -1,7 +1,8 @@ -import { afterEach, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { registerAction } from "@/platform/actions"; import { setInvokeRoute } from "@/platform/tauriCore"; -import { reloadDdl, useDatabase } from "./store"; +import { provideEditorService } from "@/workbench/contributions"; +import { detailsKey, disconnect, openDdl, prefetchDdl, reloadDdl, useDatabase } from "./store"; afterEach(() => setInvokeRoute(null)); @@ -30,3 +31,77 @@ it("reloads the DDL into the open editor of its generated file", async () => { expect(written[0]![1]).toContain("note"); expect(reloaded).toHaveBeenCalledWith([path]); }); + +describe("DDL prefetch cache", () => { + const key = detailsKey("s1", "main", "goods"); + const file = "/data/consoles/db/s1/main.goods.sql"; + let ddlCalls = 0; + let written: [string, string][] = []; + let opened: string[] = []; + let unregister: () => void; + + beforeEach(() => { + ddlCalls = 0; + written = []; + opened = []; + useDatabase.setState({ ddl: {}, ddlFiles: {}, consoles: {} }); + setInvokeRoute((cmd, args) => { + const a = args as Record; + if (cmd === "db_ddl") { + ddlCalls += 1; + return Promise.resolve("CREATE TABLE goods (id INTEGER, note TEXT);"); + } + if (cmd === "db_console_path") return Promise.resolve("/data/consoles/db/s1/console.sql"); + if (cmd === "db_export_file") { + written.push([a.path!, a.text!]); + return Promise.resolve(null); + } + return Promise.resolve(null); + }); + provideEditorService({ + openFile: async (p) => void opened.push(p), + openInput: async () => {}, + activePath: () => null, + activeCursor: () => null, + saveAll: async () => {}, + }); + unregister = registerAction({ id: "file.reloadFromDisk", title: "Reload from Disk", run: () => {} }); + }); + + afterEach(() => { + unregister(); + provideEditorService(undefined); + }); + + it("opens a prefetched DDL without querying the database again", async () => { + useDatabase.setState({ ddl: { [key]: "CACHED DDL" } }); + await openDdl("s1", "main", "goods"); + expect(ddlCalls).toBe(0); + expect(written[0]![1]).toContain("CACHED DDL"); + expect(opened).toEqual([file]); + }); + + it("fetches once on a miss and serves the next open from cache", async () => { + await openDdl("s1", "main", "goods"); + expect(ddlCalls).toBe(1); + expect(useDatabase.getState().ddl[key]).toContain("CREATE TABLE"); + await openDdl("s1", "main", "goods"); + expect(ddlCalls).toBe(1); + }); + + it("prefetch caches the DDL without opening a file, and does not refetch", async () => { + prefetchDdl("s1", "main", "goods"); + await vi.waitFor(() => expect(useDatabase.getState().ddl[key]).toContain("CREATE TABLE")); + expect(written).toEqual([]); + expect(opened).toEqual([]); + prefetchDdl("s1", "main", "goods"); + await Promise.resolve(); + expect(ddlCalls).toBe(1); + }); + + it("drops the cached DDL when the data source disconnects", async () => { + useDatabase.setState({ ddl: { [key]: "CACHED DDL" } }); + await disconnect("s1"); + expect(useDatabase.getState().ddl[key]).toBeUndefined(); + }); +}); diff --git a/src/features/database/store.ts b/src/features/database/store.ts index abf6f5b44..24a0744a8 100644 --- a/src/features/database/store.ts +++ b/src/features/database/store.ts @@ -234,6 +234,8 @@ interface DatabaseState { tables: Record>; /** `${id}\u0000${schema}\u0000${table}` → columns / indexes. */ details: Record>; + /** `${id}\u0000${schema}\u0000${table}` (+catalog) → DDL text, prefetched so Go to DDL opens at once. */ + ddl: Record; /** `${id}\u0000${schema}` → routines and sequences (loaded with the tables). */ objects: Record; /** Console / SQL file path → data source id. */ @@ -342,6 +344,7 @@ export const useDatabase = create(() => ({ schemas: {}, tables: {}, details: {}, + ddl: {}, objects: {}, consoles: readBindings(), ddlFiles: {}, @@ -694,6 +697,7 @@ function forget(id: string) { completion: dropKeys(s.completion), tables: dropKeys(s.tables), details: dropKeys(s.details), + ddl: dropKeys(s.ddl), objects: dropKeys(s.objects), }; }); @@ -2043,12 +2047,24 @@ async function writeDdl(path: string, text: string): Promise { } /** Go to DDL: the definition of a table / view, in a SQL file next to the data source's console. */ +/** Best-effort DDL prefetch so Go to DDL opens from cache; a plain call avoids connection prompts. */ +export function prefetchDdl(id: string, schema: string, table: string, catalog?: string): void { + const key = detailsKey(id, schema, table, catalog); + if (useDatabase.getState().ddl[key] !== undefined) return; + void call(commands.dbDdl(id, schema, table)) + .then((text) => useDatabase.setState((s) => ({ ddl: { ...s.ddl, [key]: text } }))) + .catch(() => undefined); +} + export async function openDdl(id: string, schema: string, name: string, catalog?: string): Promise { try { + const key = detailsKey(id, schema, name, catalog); + const cached = useDatabase.getState().ddl[key]; const [text, console] = await Promise.all([ - withConnection(id, () => call(commands.dbDdl(id, schema, name))), + cached !== undefined ? cached : withConnection(id, () => call(commands.dbDdl(id, schema, name))), call(commands.dbConsolePath(id)), ]); + if (cached === undefined) useDatabase.setState((s) => ({ ddl: { ...s.ddl, [key]: text } })); const safe = (s: string) => s.replace(/[^\w.-]+/g, "_"); const path = console.replace(/[^\\/]*$/, `${safe(schema)}.${safe(name)}.sql`); await writeDdl(path, readableDdl(text, sourceById(id)?.driver)); @@ -2073,6 +2089,8 @@ export async function reloadDdl(path: string): Promise { try { const text = await withConnection(target.id, () => call(commands.dbDdl(target.id, target.schema, target.table))); await writeDdl(path, readableDdl(text, sourceById(target.id)?.driver)); + const key = detailsKey(target.id, target.schema, target.table, target.catalog); + useDatabase.setState((s) => ({ ddl: { ...s.ddl, [key]: text } })); notifications().notify({ level: "info", title: `Reloaded the DDL of ${target.table}`, key: "db-ddl-reload" }); } catch (e) { notifications().notify({ level: "error", title: `Cannot get the DDL of ${target.table}`, body: message(e) }); diff --git a/src/features/database/table-editor.test.tsx b/src/features/database/table-editor.test.tsx index ae4c2e694..048634bd7 100644 --- a/src/features/database/table-editor.test.tsx +++ b/src/features/database/table-editor.test.tsx @@ -34,6 +34,7 @@ vi.mock("./store", () => ({ withConnection: (_id: string, run: () => unknown) => run(), openDialog: vi.fn(), openDdl: backend.openDdl, + prefetchDdl: vi.fn(), })); vi.mock("@tanstack/react-virtual", () => ({