perf(database): prefetch a table's DDL so Go to DDL opens at once (#7779)

Go to DDL queried the server on every click, so the editor opened a few hundred milliseconds late. A table's DDL is now prefetched when its data view opens and cached with the other metadata; Go to DDL serves the cache and fetches once on a miss. The cache is dropped on refresh, disconnect and after a console statement that changes the schema, and the generated file's Reload refreshes it.

Closes #7777

Co-authored-by: junchangpeng <[email protected]>
Цей коміт міститься в:
JunChang Peng authored and GitHub committed 2026-12-03 18:41:58 +08:00
1 джерело 6404c30718
коміт 9087fa61d9
4 files changed
+99 -4

No files matched your search

+2 -1
Переглянути файл
@@ -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, () =>
+77 -2
Переглянути файл
@@ -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<string, string>;
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();
});
});
+19 -1
Переглянути файл
@@ -234,6 +234,8 @@ interface DatabaseState {
tables: Record<string, Loaded<DbTableInfo[]>>;
/** `${id}\u0000${schema}\u0000${table}` → columns / indexes. */
details: Record<string, Loaded<DbTableDetails>>;
/** `${id}\u0000${schema}\u0000${table}` (+catalog) → DDL text, prefetched so Go to DDL opens at once. */
ddl: Record<string, string>;
/** `${id}\u0000${schema}` → routines and sequences (loaded with the tables). */
objects: Record<string, DbSchemaObjects>;
/** Console / SQL file path → data source id. */
@@ -342,6 +344,7 @@ export const useDatabase = create<DatabaseState>(() => ({
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<void> {
}
/** 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<void> {
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<void> {
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) });
+1
Переглянути файл
@@ -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", () => ({