feat(database): list query consoles under a Database Consoles root (#6408)

Query consoles stay in <dataDir>/consoles/db; the database feature registers that folder as a Database Consoles root in the Project view's Scratches and Consoles scope, re-registered when a remote session starts or ends. Console folders show the data source's name and icon ("Orders", "Orders: sales") through new display-only label/icon file decorations, which also order siblings when sorting by name. Consoles announce their creation so the tree refreshes, deleted console files close their editors, and a console's data source is recovered from its path when the binding is missing.

Co-authored-by: wangyuewen-china <[email protected]>
Цей коміт міститься в:
Waiting-Night authored and GitHub committed 2026-11-27 17:06:51 +08:00
1 джерело 62cc6768fe
коміт fe3e647abb
16 files changed
+220 -23

No files matched your search

+40
Переглянути файл
@@ -0,0 +1,40 @@
import type { DataSource } from "@/platform/ipc";
import { describe, expect, it } from "vitest";
import { consoleDecorations } from "./store";
describe("query console file decorations", () => {
const source = { id: "pg", name: "Orders", driver: "postgres" } as DataSource;
it("labels console folders with their data source instead of the physical data source id", () => {
const decorations = consoleDecorations({
sources: [source, { id: "analytics", name: "Analytics", driver: "postgres" } as DataSource],
consoles: {
"/data/consoles/db/pg/console.sql": "pg",
"/data/consoles/db/pg.sales/console_1.sql": "pg:sales",
},
});
// The root is registered by the database feature, not decorated as a folder path.
expect(decorations.get("/data/consoles/db")).toBeUndefined();
expect(decorations.get("/data/consoles/db/pg")).toMatchObject({ label: "Orders", icon: "db-postgres" });
// A data source whose console has not been opened still gets a readable folder name.
expect(decorations.get("/data/consoles/db/analytics")).toMatchObject({ label: "Analytics" });
expect(decorations.get("/data/consoles/db/pg.sales")).toMatchObject({
label: "Orders: sales",
icon: "db-postgres",
});
expect(decorations.get("/data/consoles/db/pg/console.sql")).toMatchObject({
tabTitle: "console [Orders]",
});
});
it("recognises Windows separators", () => {
const decorations = consoleDecorations({
sources: [source],
consoles: { "C:\\Users\\me\\data\\consoles\\db\\pg\\console.sql": "pg" },
});
expect(decorations.get("C:\\Users\\me\\data\\consoles\\db")).toBeUndefined();
expect(decorations.get("C:\\Users\\me\\data\\consoles\\db\\pg")).toMatchObject({ label: "Orders" });
});
});
+45 -2
Переглянути файл
@@ -6,8 +6,9 @@
*/
import { lazyComponent, lazyWhen, type MenuItem } from "@/ui";
import { activeEditor, lazyEditorExtension, registerEditorContribution } from "@/editor/api";
import { onFileOperation } from "@/platform/fileOps";
import { tx } from "@/platform/i18n";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { call, commands, emitLocalIdeEvent, onIdeEvent } from "@/platform/ipc";
import { registerActions, type ActionContext } from "@/platform/actions";
import { activeCellGrid } from "./cellActions";
import {
@@ -18,9 +19,11 @@ import {
type TableCommandTarget,
} from "./tableEditorFocus";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import {
registerEditorKind,
registerOverlay,
registerProjectViewRoot,
registerServiceView,
registerToolWindow,
setFileDecorations,
@@ -147,7 +150,42 @@ function registerDatabaseWindow(): () => void {
}
export function activate(): () => void {
let disposed = false;
let unregisterConsolesRoot = () => {};
let consolesDir: string | null = null;
let consolesRootGeneration = 0;
const registerConsolesRoot = () => {
const current = ++consolesRootGeneration;
unregisterConsolesRoot();
unregisterConsolesRoot = () => {};
consolesDir = null;
void call(commands.dbConsolesDir())
.then((path) => {
if (disposed || current !== consolesRootGeneration) return;
consolesDir = path;
unregisterConsolesRoot = registerProjectViewRoot({
id: "db-consoles",
label: tx("Database Consoles"),
icon: "db-folder",
path,
order: 20,
scope: "scratches",
});
})
.catch((e: unknown) => console.warn("database consoles: no consoles folder", e));
};
registerConsolesRoot();
const disposers = [
useRemote.subscribe((state, previous) => {
if (state.session !== previous.session) registerConsolesRoot();
}),
onFileOperation((op) => {
const removed =
consolesDir && op.kind === "deleted"
? op.paths.filter((path) => path === consolesDir || path.startsWith(`${consolesDir}/`))
: [];
if (removed.length) emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed });
}),
onIdeEvent("dbSourcesChanged", () => {
void loadSources();
}),
@@ -448,5 +486,10 @@ export function activate(): () => void {
},
]),
];
return () => disposers.reverse().forEach((d) => d());
return () => {
disposed = true;
consolesRootGeneration++;
unregisterConsolesRoot();
disposers.reverse().forEach((d) => d());
};
}
+5
Переглянути файл
@@ -51,4 +51,9 @@ describe("the data source a SQL file resolves against", () => {
bindConsole(file, null);
expect(consoleSource("/p/scratch.sql")).toBe("main");
});
it("recovers a query console's data source from its path", () => {
expect(consoleSource("/data/consoles/db/orders/console.sql")).toBe("orders");
expect(consoleSource("/data/consoles/db/orders.sales/console_1.sql")).toBe("orders:sales");
});
});
+40 -4
Переглянути файл
@@ -10,6 +10,7 @@ import {
IpcError,
call,
commands,
emitLocalIdeEvent,
isCancelled,
nextRequestId,
type DataSource,
@@ -276,6 +277,18 @@ function readConsoleSchemas(): Record<string, string> {
}
}
function consoleTargetFromPath(path: string, sources: readonly DataSource[]): string | null {
const folder = /(?:^|[\\/])consoles[\\/]db[\\/]([^\\/]+)[\\/]console(?:_\d+)?\.sql$/i.exec(path)?.[1];
if (!folder) return null;
const source = sources.find((candidate) => {
const id = candidate.id ?? "";
return !!id && (folder === id || folder.startsWith(`${id}.`));
});
if (!source?.id) return null;
const database = folder === source.id ? null : folder.slice(source.id.length + 1);
return database ? `${source.id}:${database}` : source.id;
}
function readViewOptions(): Pick<DatabaseState, "separateProceduresAndFunctions" | "showTableComments"> {
try {
const raw = localStorage.getItem(VIEW_OPTIONS_KEY);
@@ -773,19 +786,32 @@ export function watchIdleConnections(everyMs = 5000): () => void {
/** Managed consoles show their source in the tab. Ordinary SQL files can also inherit a source tint. */
export function consoleDecorations(s: Pick<DatabaseState, "consoles" | "sources">): Map<string, FileDecoration> {
const out = new Map<string, FileDecoration>();
const roots = new Set<string>();
for (const [path, target] of Object.entries(s.consoles)) {
const { id, database } = splitTarget(target);
const source = s.sources.find((x) => x.id === id);
if (!source) continue;
const tint = colorVar(source.color);
// db_console_path and db_consoles own this directory, including already saved consoles.
const consoleName = /(?:^|\/)consoles\/db\/[^/]+\/(console(?:_\d+)?)\.sql$/.exec(path.replaceAll("\\", "/"))?.[1];
if (consoleName) {
const match = /[\\/]consoles[\\/]db[\\/][^\\/]+[\\/](console(?:_\d+)?)\.sql$/i.exec(path);
if (match) {
const folder = path.replace(/[\\/]console(?:_\d+)?\.sql$/i, "");
const root = folder.replace(/[\\/][^\\/]+$/, "");
const name = source.name || id;
const label = database ? `${name}: ${database}` : name;
out.set(path, { tint, tabTitle: `${consoleName} [${label}]`, tabIcon: sourceIcon(source) });
const icon = sourceIcon(source);
out.set(path, { tint, tabTitle: `${match[1]} [${label}]`, tabIcon: icon });
out.set(folder, { label, icon });
roots.add(root);
} else if (tint) out.set(path, { tint });
}
for (const root of roots) {
const separator = root.includes("\\") ? "\\" : "/";
for (const source of s.sources) {
if (!source.id) continue;
out.set(`${root}${separator}${source.id}`, { label: source.name || source.id, icon: sourceIcon(source) });
}
}
return out;
}
@@ -1163,6 +1189,8 @@ export function consoleSource(path: string): string | null {
const s = useDatabase.getState();
const bound = s.consoles[path];
if (bound && s.sources.some((x) => x.id === splitTarget(bound).id)) return bound;
const inferred = consoleTargetFromPath(path, s.sources);
if (inferred) return inferred;
const scope = scopeOf(path);
if (scope) return scope.dataSource;
return s.sources.length === 1 ? (s.sources[0]!.id ?? null) : null;
@@ -1173,6 +1201,7 @@ export async function openConsole(id: string, schema?: string): Promise<void> {
try {
const path = await call(commands.dbConsolePath(id));
bindConsole(path, id);
announceConsoleFile(path);
if (schema) setConsoleSchema(path, schema);
await editorService().openFile(path, { focus: true });
} catch (e) {
@@ -1198,12 +1227,19 @@ export async function newConsole(id: string, schema?: string): Promise<void> {
const before = new Set(await consoleFiles(id));
const after = await call(commands.dbConsoles(id, true));
const path = after.find((p) => !before.has(p)) ?? after[after.length - 1];
if (path) await openConsoleFile(id, path, schema);
if (path) {
announceConsoleFile(path);
await openConsoleFile(id, path, schema);
}
} catch (e) {
notifications().notify({ level: "error", title: "Cannot open the query console", body: message(e) });
}
}
function announceConsoleFile(path: string) {
emitLocalIdeEvent({ type: "fsChanged", created: [path], modified: [], removed: [] });
}
let nextTab = 1;
let nextRun = 1;
let nextLine = 1;
+7 -2
Переглянути файл
@@ -10,8 +10,13 @@ vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
commands: { ...actual.commands, dbSources: () => "dbSources" },
call: (request: unknown) => (request === "dbSources" ? mocks.sources() : Promise.reject(new Error("unmocked"))),
commands: { ...actual.commands, dbSources: () => "dbSources", dbConsolesDir: () => "dbConsolesDir" },
call: (request: unknown) =>
request === "dbSources"
? mocks.sources()
: request === "dbConsolesDir"
? Promise.resolve("/data/consoles/db")
: Promise.reject(new Error("unmocked")),
};
});