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

+11 -1
Переглянути файл
@@ -612,7 +612,16 @@ pub fn db_consoles(host: &Host, id: String, create: bool) -> IdeResult<Vec<IpcPa
Ok(out)
}
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database, `<id>.<database>` for the others.
/// The project view root for every data source's query consoles (`<dataDir>/consoles/db`).
#[command(trust = always)]
pub fn db_consoles_dir(host: &Host) -> IdeResult<IpcPath> {
let dir = host.data_dir.join("consoles").join("db");
std::fs::create_dir_all(&dir)?;
Ok(dir.into())
}
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database,
/// `<id>.<database>` for the others.
fn console_dir(host: &Host, id: &str) -> IdeResult<PathBuf> {
let (source, database) = ide_db::split_target(id);
if source.is_empty() || !source.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
@@ -670,6 +679,7 @@ ide_command::domain!(
db_connect,
db_connected,
db_console_path,
db_consoles_dir,
db_consoles,
db_create_database,
db_database_catalog,
+14 -1
Переглянути файл
@@ -9,12 +9,15 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let host = Arc::new(Host::new(common::host_config(base)));
let root = base.join("data/consoles/db/pg");
let names = |paths: Vec<ide_core::IpcPath>| -> Vec<String> {
paths.iter().map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()).collect()
};
assert!(db::db_consoles(&host, "pg".into(), false).unwrap().is_empty());
// The first new console is the default one, then console_1, console_2…
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql"]);
let first = db::db_consoles(&host, "pg".into(), true).unwrap();
assert_eq!(names(first.clone()), ["console.sql"]);
assert_eq!(first[0].0, root.join("console.sql"));
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql", "console_1.sql"]);
let all = db::db_consoles(&host, "pg".into(), true).unwrap();
assert_eq!(names(all.clone()), ["console.sql", "console_1.sql", "console_2.sql"]);
@@ -26,3 +29,13 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
assert!(db::db_consoles(&host, "pg:other".into(), false).unwrap().is_empty());
assert!(db::db_consoles(&host, "../x".into(), true).is_err());
}
#[tokio::test]
async fn consoles_root_is_the_directory_listed_in_the_project_view() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let host = Arc::new(Host::new(common::host_config(base)));
let root = db::db_consoles_dir(&host).unwrap();
assert_eq!(root.0, base.join("data/consoles/db"));
assert!(root.0.is_dir());
}
+1
Переглянути файл
@@ -423,6 +423,7 @@ async fn local_deployment_runs_on_the_project_host() {
"db_table_page",
"db_apply_edits",
"db_console_path",
"db_consoles_dir",
"db_consoles",
"ssh_test",
"ssh_set_secret",
+1 -1
Переглянути файл
@@ -125,7 +125,7 @@ These keys work while the Database tree has focus. The context menu also has **T
## Query console
Each data source has a query console, a `.sql` file kept in the IDE's data directory. Open it with **Query Console** (`⌘⇧L` / `Ctrl+Shift+Q`), from the tree, or with **Tools › Open Query Console**. Any writable `.sql` file in the project gets the same toolbar, so you can bind it to a data source and run it. In **Recent Files** (`⌘E` / `Ctrl+E`) a console shows its data source name, such as `console [Orders]`.
Each data source has a query console, a `.sql` file kept under `consoles/db` in the IDE's data directory and listed under the **Database Consoles** root in **Scratches and Consoles**, grouped by data source name. Open it with **Query Console** (`⌘⇧L` / `Ctrl+Shift+Q`), from the tree, or with **Tools › Open Query Console**. Any writable `.sql` file in the project gets the same toolbar, so you can bind it to a data source and run it. In **Recent Files** (`⌘E` / `Ctrl+E`) a console shows its data source name, such as `console [Orders]`.
The console toolbar has:
+1 -1
Переглянути файл
@@ -125,7 +125,7 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行
## 查询控制台
每个数据源都有一个查询控制台,它是保存在 IDE 数据目录中的 `.sql` 文件。可以用 **查询控制台**(`⌘⇧L` / `Ctrl+Shift+Q`)、从树中或通过 **工具 › Open Query Console** 打开。项目中任何可写的 `.sql` 文件也有同样的工具栏,绑定数据源后即可执行。在 **最近的文件**(`⌘E` / `Ctrl+E`)中,控制台会显示所属数据源,例如 `console [Orders]`。
每个数据源都有一个查询控制台,它是保存在 IDE 数据目录 `consoles/db` 下的 `.sql` 文件,并显示在 **临时文件和控制台** 的 **数据库控制台** 根节点下,按数据源名称分组。可以用 **查询控制台**(`⌘⇧L` / `Ctrl+Shift+Q`)、从树中或通过 **工具 › Open Query Console** 打开。项目中任何可写的 `.sql` 文件也有同样的工具栏,绑定数据源后即可执行。在 **最近的文件**(`⌘E` / `Ctrl+E`)中,控制台会显示所属数据源,例如 `console [Orders]`。
控制台工具栏:
+1
Переглянути файл
@@ -114,6 +114,7 @@ db_connect trusted project_host bin
db_connected trusted project_host bindings sync
db_console_path always project_host bindings sync
db_consoles always project_host bindings sync
db_consoles_dir always project_host bindings sync
db_create_database trusted project_host bindings async
db_database_catalog trusted project_host bindings async
db_databases trusted project_host bindings async
+2
Переглянути файл
@@ -357,6 +357,8 @@ export const commands = {
dbConsolePath: (id: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("db_console_path", { id })),
/** The query consoles of data source `id`; `create` adds the next one first. */
dbConsoles: (id: string, create: boolean) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("db_consoles", { id, create })),
/** The project view root for every data source's query consoles (`<dataDir>/consoles/db`). */
dbConsolesDir: () => typedError<IpcPath, IdeError>(__TAURI_INVOKE("db_consoles_dir")),
dbCreateDatabase: (id: string, template: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_create_database", { id, template, statement })),
dbDatabaseCatalog: (id: string, database: string) => typedError<DbCatalogSchema[], IdeError>(__TAURI_INVOKE("db_database_catalog", { id, database })),
dbDatabases: (id: string) => typedError<DbDatabases, IdeError>(__TAURI_INVOKE("db_databases", { id })),
+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")),
};
});
+13
Переглянути файл
@@ -1164,6 +1164,19 @@ it("shows a decoration's suffix after the root name, with icons and struck-out s
await waitFor(() => expect(row("acme").textContent).not.toContain("main/"));
});
it("shows a decoration's display label and icon in place of the physical name", async () => {
const { row } = setup();
await waitFor(() => expect(row("src")).toBeTruthy());
act(() => setFileDecorations("test-label", new Map([[`${ROOT}/src`, { label: "Orders", icon: "db-postgres" }]])));
await waitFor(() => expect(row("Orders")).toBeTruthy());
const content = row("Orders").querySelector("[data-project-path]");
expect(content).toHaveAttribute("data-project-path", `${ROOT}/src`);
expect(content).toHaveAttribute("data-project-icon", "db-postgres");
expect(screen.queryByText("src")).not.toBeInTheDocument();
act(() => setFileDecorations("test-label", new Map()));
await waitFor(() => expect(row("src")).toBeTruthy());
});
it("marks file and folder symlinks with the link arrow, leaving real folders and files alone", async () => {
fs = new MemoryFs(
{
+35 -11
Переглянути файл
@@ -30,8 +30,10 @@ import { useDetectedRoots, useEffectiveRoots } from "@/platform/projectRoots";
import { macStroke, strokeOf } from "@/platform/keymap";
import {
OWNS_FILE_DROP,
getFileDecoration,
prepareMenuGroups,
useFileDecoration,
useFileDecorations,
type DecorationSegment,
} from "@/workbench/contributions";
import { useFileColors } from "@/workbench/fileColors";
@@ -71,7 +73,7 @@ import { relativePath } from "@/platform/project";
import { folderKind } from "./folderKind";
import { PROJECT_TYPES } from "@/ui/projectType";
import { useHomeDir } from "./home";
import { keyLike, memberNodes, nodeKeyFor, visibleInfo, type ProjectNode } from "./model";
import { compareNames, keyLike, memberNodes, nodeKeyFor, visibleInfo, type ProjectNode } from "./model";
import {
cancelEditing,
checkEditingName,
@@ -127,7 +129,8 @@ export function showNewPopup(): boolean {
}
const getKey = (n: ProjectNode) => n.key;
const getLabel = (n: ProjectNode) => n.label;
const getLabel = (n: ProjectNode) =>
n.placeholder || n.member ? n.label : (getFileDecoration(n.path)?.label ?? n.label);
function iconFor(
node: ProjectNode,
@@ -298,11 +301,13 @@ const Row = memo(function Row({
const file = useJvmPresentation(node.dir || node.placeholder ? "" : node.path, node.entry?.mtimeMs);
const expanded = useProjectTree((s) => node.dir && s.expanded.has(node.key));
const holdsOpen = useProjectTree((s) => node.dir && holdsOpenFile(node.path, s.openFiles));
const icon = projectType
? PROJECT_TYPES[projectType].icon
: node.dir || node.placeholder || node.icon
? iconFor(node, roots, root, build, detected, expanded, holdsOpen)
: presentationIcon(node.path, file, roots, root, build.spring);
const icon =
deco.icon ??
(projectType
? PROJECT_TYPES[projectType].icon
: node.dir || node.placeholder || node.icon
? iconFor(node, roots, root, build, detected, expanded, holdsOpen)
: presentationIcon(node.path, file, roots, root, build.spring));
const moduleFolder =
node.dir && !node.placeholder && !!root && isModuleFolder(relativePath(root, node.path), node.root, build.modules);
const isEditing =
@@ -310,6 +315,7 @@ const Row = memo(function Row({
const faded = node.ignored || deco.faded;
// IDEA dims the icon of excluded folders only; git-ignored ones just get the ignored colour.
const dimIcon = node.excluded;
const label = deco.label ?? node.label;
return (
<span
className={clsx(styles.content, cut && styles.cut, dropTarget && styles.dropTarget)}
@@ -354,7 +360,7 @@ const Row = memo(function Row({
deco.error && styles.error,
)}
style={deco.color ? { color: deco.color } : undefined}
text={node.label}
text={label}
indices={matches}
tone="accent"
/>
@@ -479,6 +485,8 @@ export function ProjectView() {
const txTemplate = useTxTemplate();
// Rows compute their file icons while rendering: redraw when the icon theme changes.
useFileIconRevision();
// Display aliases (data source names for console folders) also decide sibling order.
const decorationProviders = useFileDecorations((s) => s.providers);
const root = useProjectTree((s) => s.root);
const model = useProjectTree(selectModel);
const fileColors = useFileColors("projectView");
@@ -572,9 +580,25 @@ export function ProjectView() {
);
const getChildren = useCallback(
(n: ProjectNode) =>
n.member ? memberNodes(n.path, n.member.children) : n.dir ? model.children.get(n.key) : outlineRows.get(n.path),
[model, outlineRows],
(n: ProjectNode) => {
if (n.member) return memberNodes(n.path, n.member.children);
if (!n.dir) return outlineRows.get(n.path);
const children = model.children.get(n.key);
if (
!children ||
!decorationProviders.size ||
options.sortBy !== "name" ||
!children.some((child) => getLabel(child) !== child.label)
)
return children;
const labels = new Map(children.map((child) => [child, getLabel(child)]));
return [...children].sort((a, b) => {
if (!!a.placeholder !== !!b.placeholder) return a.placeholder ? -1 : 1;
if (options.foldersFirst && a.dir !== b.dir) return a.dir ? -1 : 1;
return compareNames(labels.get(a)!, labels.get(b)!);
});
},
[decorationProviders, model, options.foldersFirst, options.sortBy, outlineRows],
);
const onExpandedChange = useCallback((next: Set<string>, node: ProjectNode, open: boolean) => {
+1
Переглянути файл
@@ -1707,6 +1707,7 @@
"Data type": "数据类型",
"Database": "数据库",
"Database actions": "数据库操作",
"Database Consoles": "数据库控制台",
"Database output": "数据库输出",
"Database:": "数据库:",
"Date": "日期",
+3
Переглянути файл
@@ -1238,6 +1238,9 @@ export interface FileDecoration {
/** Display name and icon for a specialized file tab. The path still identifies the document. */
tabTitle?: string;
tabIcon?: string;
/** Display name and icon for a Project view row. The path still identifies the file or folder. */
label?: string;
icon?: string;
/** Short badge text, e.g. a problem count. */
badge?: string;
tooltip?: string;