Files
openidea/src/features/database/index.ts
T
l0ng-ai ad8df8fe00 feat(database): open several query consoles per data source (#3386)
New › Query Console always reopened the single console of a data source. It now creates another console each time (console, console_1, console_2…, as in DataGrip); Jump to Query Console opens the only console directly or lists them with New Query Console; Tools › Query Console keeps opening the default one. Backend: db_consoles(id, create).
2026-11-14 22:50:51 +08:00

322 lines
11 KiB
TypeScript

/**
* Database tools (IDEA's Database tool window, scoped): data sources for
* SQLite / PostgreSQL / MySQL-MariaDB, a schema tree, query consoles with
* results grids, and a table data editor. Connections, introspection and
* statements run in Rust (`ide-db`).
*/
import { lazyComponent, lazyWhen, type MenuItem } from "@/ui";
import { activeEditor, lazyEditorExtension, registerEditorContribution } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { onIdeEvent } from "@/platform/ipc";
import { registerActions } from "@/platform/actions";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
import { useProject } from "@/platform/project";
import {
registerEditorKind,
registerOverlay,
registerServiceView,
registerToolWindow,
setFileDecorations,
toolWindowService,
} from "@/workbench/contributions";
import { installCellActions } from "./cellActions";
import { installValueEditorActions } from "./valueEditorActions";
import { registerResultTabActions } from "./resultTabActions";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { TABLE_KIND, tableTitle } from "./tableInput";
import { databaseRequest, projectRequest } from "./requests";
import { nodeTarget, type DbNode } from "./nodes";
import { registerDatabaseTreeActions } from "./treeActions";
import {
DB_TOOL_WINDOW,
RESULTS_VIEW,
consoleSource,
consoleTints,
loadSources,
connect,
loadSchemas,
loadDatabases,
listsDatabases,
sourceById,
newConsole,
openConsole,
openHistory,
openSourceDialog,
useDatabase,
watchIdleConnections,
} from "./store";
function useDatabaseHeaderMenu(): MenuItem[] {
const separate = useDatabase((s) => s.separateProceduresAndFunctions);
return [{ kind: "action", action: "db.separateProceduresAndFunctions", checked: separate }];
}
const useDialogOpen = () => useDatabase((s) => !!s.dialog);
export function activate(): () => void {
const disposers = [
onIdeEvent("dbSourcesChanged", () => {
void loadSources();
}),
registerToolWindow({
id: DB_TOOL_WINDOW,
title: "Database",
icon: "toolwindow-database",
anchor: "right",
order: 20,
component: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseView)),
headerMenu: useDatabaseHeaderMenu,
headerActions: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseHeaderActions)),
}),
registerServiceView({
id: RESULTS_VIEW,
title: "Database",
icon: "database",
order: 20,
onUse: true,
component: lazyComponent(() => import("./ResultsView").then((m) => m.ResultsView)),
}),
registerEditorKind({
kind: TABLE_KIND,
component: lazyComponent(() => import("./TableEditor").then((m) => m.TableEditor)),
title: tableTitle,
icon: () => "database",
}),
registerOverlay({
id: "database.dialogs",
component: lazyWhen(useDialogOpen, () => import("./Dialogs").then((m) => m.DatabaseDialogs)),
}),
registerEditorContribution({
id: "database.console",
order: 57,
extensions: lazyEditorExtension(
(ctx) => ctx.language === SQL_LANGUAGE && !ctx.virtual && !ctx.readOnly,
() => import("./console").then((m) => m.consoleExtension),
),
}),
// A reopened project starts with a fresh backend: forget the old one's state.
useProject.subscribe((s, prev) => {
if (s.project?.root === prev.project?.root) return;
useDatabase.setState({
sources: [],
loaded: false,
connected: new Set(),
databases: {},
catalogs: {},
schemas: {},
tables: {},
details: {},
objects: {},
completion: {},
results: [],
output: [],
activeResult: null,
selectedSource: null,
selectedNode: null,
treeExpanded: new Set(),
treeReveal: null,
manualCommit: new Set(),
pendingTx: new Set(),
running: {},
dialog: null,
newMenuOpen: false,
});
}),
// Consoles of coloured data sources get a tinted tab.
useDatabase.subscribe((s, prev) => {
if (s.consoles !== prev.consoles || s.sources !== prev.sources) setFileDecorations("database", consoleTints(s));
}),
() => setFileDecorations("database", new Map()),
watchIdleConnections(),
installTableEditorFocus(),
installValueEditorActions(),
installCellActions(),
registerResultTabActions(),
registerDatabaseTreeActions(),
registerActions([
{
id: "db.pluginConnect",
title: "Connect Plugin Data Source",
category: "Tools",
when: "projectOpen",
run: async (e) => {
if (!useProject.getState().project?.trusted)
throw new Error(tx("Trust this project to connect plugin data sources"));
const id = e.arg;
if (typeof id !== "string") throw new Error(tx("Invalid data source id"));
const project = projectRequest();
await loadSources();
if (!project()) return;
const current = databaseRequest(id);
toolWindowService().show(DB_TOOL_WINDOW, true);
const connected = await connect(id);
if (!current()) return;
if (!connected) throw new Error(tx("Database connection failed"));
if (listsDatabases(sourceById(id))) await loadDatabases(id);
else await loadSchemas(id);
},
},
{
id: "db.showToolWindow",
title: "Database",
category: "Tools",
icon: "toolwindow-database",
keywords: ["data sources", "sql", "tables"],
when: "projectOpen",
run: () => toolWindowService().show(DB_TOOL_WINDOW, true),
},
{
id: "db.newDataSource",
title: "New Data Source…",
category: "Tools",
icon: "plus",
keywords: ["database", "connection", "postgres", "mysql", "sqlite"],
when: "projectOpen",
run: async () => {
const current = projectRequest();
if (!useDatabase.getState().loaded) await loadSources();
if (!current()) return;
openSourceDialog(null);
},
},
{
id: "db.openConsole",
title: "Query Console",
category: "Tools",
icon: "file-sql",
keywords: ["database", "sql console"],
when: "projectOpen",
run: async ({ arg }) => {
const current = projectRequest();
const s = useDatabase.getState();
if (!s.loaded) await loadSources();
if (!current()) return;
const { sources, selectedSource } = useDatabase.getState();
// A tree node (New ▸ Query Console) opens its data source's console.
const node = arg && typeof arg === "object" && "kind" in arg ? nodeTarget(arg as DbNode) : null;
const id = node ?? selectedSource ?? (sources.length === 1 ? sources[0]!.id : null);
if (id) await openConsole(id);
else toolWindowService().show(DB_TOOL_WINDOW, true);
},
},
{
id: "db.newConsole",
title: "New Query Console",
category: "Tools",
icon: "db-console",
keywords: ["database", "sql console"],
when: "projectOpen",
run: async ({ arg }) => {
const current = projectRequest();
if (!useDatabase.getState().loaded) await loadSources();
if (!current()) return;
const { sources, selectedSource } = useDatabase.getState();
const node = arg && typeof arg === "object" && "kind" in arg ? nodeTarget(arg as DbNode) : null;
const id = node ?? selectedSource ?? (sources.length === 1 ? sources[0]!.id : null);
if (id) await newConsole(id);
else toolWindowService().show(DB_TOOL_WINDOW, true);
},
},
{
id: "db.execute",
title: "Execute SQL Statement",
category: "Tools",
icon: "run",
when: `editorTextFocus && editorLangId == ${SQL_LANGUAGE}`,
run: async () => {
const current = projectRequest();
const e = activeEditor();
if (!e || e.ctx.language !== SQL_LANGUAGE) return;
if (!useDatabase.getState().loaded) await loadSources();
if (!current()) return;
if (!consoleSource(e.ctx.path) && !useDatabase.getState().sources.length) {
openSourceDialog(null);
return;
}
await (await import("./console")).executeInView(e.view, e.ctx.path);
},
},
{
id: "db.executeScript",
title: "Execute SQL Script",
category: "Tools",
icon: "gutter-run-all",
keywords: ["run all", "whole file", "statements"],
when: `editorTextFocus && editorLangId == ${SQL_LANGUAGE}`,
run: async () => {
const current = projectRequest();
const e = activeEditor();
if (!e || e.ctx.language !== SQL_LANGUAGE) return;
if (!useDatabase.getState().loaded) await loadSources();
if (!current()) return;
if (!consoleSource(e.ctx.path) && !useDatabase.getState().sources.length) {
openSourceDialog(null);
return;
}
await (await import("./console")).executeScriptInView(e.view, e.ctx.path);
},
},
{
id: "db.goToColumn",
title: "Go to Column",
category: "Tools",
keywords: ["table editor", "file structure", "columns"],
when: "dbTableEditorFocus",
run: () => activeTableEditor()?.showColumns(),
},
{
id: "db.submitChanges",
title: "Submit",
category: "Tools",
keywords: ["table editor", "apply changes", "commit"],
when: "dbTableEditorFocus && dbTableEditorChanges",
run: () => activeTableEditor()?.submit(),
},
{
id: "db.revertChanges",
title: "Revert",
category: "Tools",
keywords: ["table editor", "discard changes", "undo"],
when: "dbTableEditorFocus && dbTableEditorChanges",
run: () => activeTableEditor()?.revert(),
},
{
id: "db.explainPlan",
title: "Explain Plan",
category: "Tools",
icon: "db-plan",
keywords: ["query plan", "explain", "sql"],
when: `editorTextFocus && editorLangId == ${SQL_LANGUAGE}`,
run: async () => {
const current = projectRequest();
const e = activeEditor();
if (!e || e.ctx.language !== SQL_LANGUAGE) return;
if (!useDatabase.getState().loaded) await loadSources();
if (!current()) return;
await (await import("./console")).explainInView(e.view, e.ctx.path);
},
},
{
id: "db.queryHistory",
title: "Browse Query History",
category: "Tools",
icon: "history",
keywords: ["database", "sql", "history"],
when: "projectOpen",
run: async () => {
const current = projectRequest();
if (!useDatabase.getState().loaded) await loadSources();
if (!current()) return;
const e = activeEditor();
const path = e?.ctx.language === SQL_LANGUAGE ? e.ctx.path : null;
const s = useDatabase.getState();
const id =
(path && consoleSource(path)) ?? s.selectedSource ?? (s.sources.length === 1 ? s.sources[0]!.id : null);
openHistory(path, id ?? null);
},
},
]),
];
return () => disposers.reverse().forEach((d) => d());
}