Файли
openidea/src/features/database/treeActions.ts
T
Vladislav Kuzmin bd396485c2 feat(database): support DuckDB SQL and browse attached catalogs (#6254)
DuckDB sources get DuckDB's SQL dialect (highlighting, completion, formatting and resolution) and the database tree lists attached catalogs with their schemas, tables and columns. The JDBC bridge gains a catalogs command and catalog-scoped schema and table metadata, matched by exact catalog and schema names; tables in another catalog open and page through the source session. DDL that attaches, detaches or changes a catalog refreshes the tree.

Co-authored-by: principalwater <[email protected]>
2026-11-28 09:07:53 +08:00

855 рядки
30 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
/**
* Actions of the Database tool window (IDEA's Database view actions): they
* act on the node passed as the argument (context menus) or on the tree's
* lead node (toolbar, shortcuts while the tree has focus).
*/
import { introspectSource } from "./introspection";
import { writeClipboardText } from "@/platform/clipboard";
import { call, commands, type DataSource, type DbDriver, type DbTableInfo } from "@/platform/ipc";
import { readDesktopText } from "@/platform/desktopFiles";
import { registerActions, type Action } from "@/platform/actions";
import { editorService, notifications, showServiceView, toolWindowService } from "@/workbench/contributions";
import { splitTarget } from "./model";
import { nodeTarget, objectOf, schemaObjectOf, tableFolder, tableOf, type DbNode } from "./nodes";
import { canDrop, canModifyTable, canRename, quoteIdent, reference, scriptSql, type ScriptKind } from "./objects";
import {
DB_TOOL_WINDOW,
OUTPUT_TAB,
connect,
connectedTargets,
createsDatabases,
RESULTS_VIEW,
detailsKey,
disconnect,
duplicateSource,
loadDetails,
loadSchemas,
loadSources,
loadTables,
consoleFiles,
newSchemaTarget,
newConsole,
openConsole,
openConsoleFile,
openConsoleWith,
openDdl,
openObjectDdl,
openDialog,
openSourceDialog,
readableDdl,
refresh,
removeSourceFolder,
revealInTree,
revealOpened,
runSql,
sourceById,
tablesKey,
toggleSeparateProceduresAndFunctions,
toggleShowTableComments,
useDatabase,
withConnection,
removeSources,
} from "./store";
import { tableInput } from "./tableInput";
import { DIAGRAM_TABLE_LIMIT, diagramInput, type DiagramData, type DiagramTable } from "./erDiagram";
import { dumpScope, mysqlDumpScope } from "./dumpTools";
import { tx } from "@/platform/i18n";
import { chooseItem } from "@/workbench/inputDialogs";
import { databaseRequest } from "./requests";
/** Context key: the Database tree has focus. */
export const DB_VIEW_FOCUS = "databaseViewFocus";
/** Set while the Database view is mounted: Expand All walks its tree's loaded nodes. */
export const databaseTree: { expandAll: (() => void) | null } = { expandAll: null };
const OPEN = "projectOpen";
const isNode = (v: unknown): v is DbNode => !!v && typeof v === "object" && "kind" in v && "key" in v;
/** The node an action runs on: its argument, else the tree's lead node. */
function nodeFrom(arg: unknown): DbNode | null {
return isNode(arg) ? arg : useDatabase.getState().selectedNode;
}
function driverOf(id: string): DbDriver {
return sourceById(id)?.driver ?? "sqlite";
}
function sourceOf(n: DbNode | null): DataSource | undefined {
return n ? sourceById(nodeTarget(n)) : undefined;
}
/** Copies `text`; `failure` is the notification title when the clipboard refuses it. */
async function copy(text: string, failure: string) {
try {
await writeClipboardText(text);
} catch {
notifications().notify({ level: "error", title: failure });
}
}
/** Where Quick Documentation opens: below the tree's selected row. */
function rowAnchor(): { x: number; y: number } {
const row = document.querySelector(
'[role="tree"][aria-label="Data sources"] [role="treeitem"][aria-selected="true"]',
);
const r = row?.getBoundingClientRect();
return r ? { x: r.left + 24, y: r.bottom + 2 } : { x: window.innerWidth / 2, y: window.innerHeight / 3 };
}
export function openTableData(id: string, schema: string, table: string, catalog?: string) {
void editorService().openInput(tableInput(id, schema, table, catalog), { focus: true });
}
/** Tables of a schema, loading them if needed. */
async function tablesIn(id: string, schema: string): Promise<DbTableInfo[]> {
if (useDatabase.getState().tables[tablesKey(id, schema)]?.status !== "ok") await loadTables(id, schema);
const l = useDatabase.getState().tables[tablesKey(id, schema)];
return l?.status === "ok" ? l.value : [];
}
/** The nodes an action on `arg` runs on: the tree's selection when `arg` is part of it. */
function nodesFrom(arg: unknown): DbNode[] {
const { selectedNodes } = useDatabase.getState();
if (!isNode(arg)) return selectedNodes;
return selectedNodes.some((n) => n.key === arg.key) ? selectedNodes : [arg];
}
function sourceIdsFrom(arg: unknown): string[] {
return nodesFrom(arg).flatMap((node) => {
const id = node.kind === "source" ? node.source.id : null;
return id ? [id] : [];
});
}
/** Selected data source roots; nested schema/table rows in a range selection are ignored. */
function sourcesFrom(arg: unknown): Extract<DbNode, { kind: "source" }>[] {
const seen = new Set<string>();
return nodesFrom(arg).flatMap((node) => {
if (node.kind !== "source") return [];
const id = node.source.id ?? "";
if (!id || seen.has(id)) return [];
seen.add(id);
return [node];
});
}
function failureText(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
/** Refreshes every selected data source in parallel and reports failures once. */
async function refreshSources(sources: Extract<DbNode, { kind: "source" }>[]): Promise<void> {
const failures: string[] = [];
await Promise.all(
sources.map(async (source) => {
try {
await refresh(source.source.id ?? "");
} catch (e) {
failures.push(`${source.source.name}: ${failureText(e)}`);
}
}),
);
if (failures.length) {
const failed = failures.length;
const total = sources.length;
notifications().notify({
level: "error",
title: tx`Failed to refresh ${failed} of ${total} data sources`,
body: failures.slice(0, 6).join("\n"),
});
}
}
/** Disconnects the connected data sources among `sources`, keeping successful deactivations. */
async function deactivateSources(sources: Extract<DbNode, { kind: "source" }>[]): Promise<void> {
const connected = sources.filter((source) => connectedTargets(source.source.id ?? "").length > 0);
if (!connected.length) return;
const results = await Promise.allSettled(connected.map((source) => disconnect(source.source.id ?? "")));
const failures = results.flatMap((result, i) =>
result.status === "rejected" ? [`${connected[i]!.source.name}: ${failureText(result.reason)}`] : [],
);
if (failures.length) {
const failed = failures.length;
const total = connected.length;
notifications().notify({
level: "error",
title: tx`Failed to deactivate ${failed} of ${total} data sources`,
body: failures.slice(0, 6).join("\n"),
});
}
}
/**
* Diagrams › Show Diagram (in a tab) and Show Diagram Popup: the selected
* tables and views, and the tables of selected schemas and table folders.
*/
async function showDiagram(nodes: DbNode[], popup: boolean): Promise<void> {
const refs = new Map<string, { id: string; schema: string; name: string }>();
const add = (id: string, schema: string, name: string) =>
refs.set(detailsKey(id, schema, name), { id, schema, name });
for (const n of nodes) {
if ("catalog" in n && n.catalog !== undefined) continue;
if (n.kind === "table") add(n.id, n.schema, n.table.name);
else if (
n.kind === "schema" ||
(n.kind === "folder" && ["tables", "views", "materializedViews"].includes(n.folder))
)
// oxlint-disable-next-line no-await-in-loop -- one schema at a time: its tables load over the same connection
for (const t of await tablesIn(n.id, n.schema))
if (n.kind === "schema" ? t.kind === "table" : tableFolder(t.kind) === n.folder) add(n.id, n.schema, t.name);
}
const all = [...refs.values()];
if (!all.length) return;
const shown = all.slice(0, DIAGRAM_TABLE_LIMIT);
const missing = shown.filter(
(t) => useDatabase.getState().details[detailsKey(t.id, t.schema, t.name)]?.status !== "ok",
);
await Promise.all(missing.map((t) => loadDetails(t.id, t.schema, t.name)));
const { details } = useDatabase.getState();
const tables = shown.flatMap((t): DiagramTable[] => {
const d = details[detailsKey(t.id, t.schema, t.name)];
return d?.status === "ok" ? [{ ...t, details: d.value }] : [];
});
if (!tables.length) return;
const [limit, total] = [tables.length, all.length];
if (total > limit)
notifications().notify({
level: "info",
title: tx`Showing the first ${limit} of ${total} tables in the diagram`,
key: "db-diagram-limit",
});
const one = nodes.length === 1 ? nodes[0]! : null;
const title = one?.kind === "table" ? one.table.name : one && "schema" in one ? one.schema : tx("Diagram");
const data: DiagramData = { title, tables };
if (popup) openDialog({ kind: "diagram", data });
else void editorService().openInput(diagramInput(data), { focus: true });
}
/**
* Connects to `target` before a dump / restore dialog opens (a password prompt would replace
* the dialog) and reads the server's version; `undefined` when the user cancelled.
*/
async function serverVersionOf(target: string): Promise<number | null | undefined> {
if (!(await connect(target))) return undefined;
try {
return await withConnection(target, () => call(commands.dbServerVersion(target)));
} catch {
return null;
}
}
/** DDL of a table / view, or of every table and view of a schema or data source. */
async function ddlOf(n: DbNode): Promise<{ id: string; text: string } | null> {
const id = nodeTarget(n);
if (!id) return null;
const current = databaseRequest(id);
const one = async (schema: string, table: string) =>
readableDdl(await withConnection(id, () => call(commands.dbDdl(id, schema, table))), driverOf(id));
try {
const o = schemaObjectOf(n);
if (o) {
const text = await withConnection(id, () => call(commands.dbObjectDdl(id, o.schema, o.kind, o.name)));
return current() ? { id, text } : null;
}
const t = tableOf(n);
if (t) {
const text = await one(t.schema, t.table);
return current() ? { id, text } : null;
}
let schemas: string[] = [];
if (n.kind === "schema" || n.kind === "folder") schemas = [n.schema];
else if (n.kind === "source" || n.kind === "database") {
if (useDatabase.getState().schemas[id]?.status !== "ok") await loadSchemas(id);
if (!current()) return null;
const l = useDatabase.getState().schemas[id];
schemas = l?.status === "ok" ? l.value : [];
}
const parts: string[] = [];
for (const schema of schemas) {
// oxlint-disable-next-line no-await-in-loop -- schemas load in turn so cancellation is checked after each schema and DDL stays grouped by schema
const tables = (await tablesIn(id, schema)).filter(
(t) => n.kind !== "folder" || tableFolder(t.kind) === n.folder,
);
if (!current()) return null;
// Tables before views: views select from them.
tables.sort((a, b) => Number(a.kind !== "table") - Number(b.kind !== "table"));
for (const t of tables) {
// oxlint-disable-next-line no-await-in-loop -- DDL text is appended in table order (tables before views) and stops when the request is superseded
parts.push(await one(schema, t.name));
if (!current()) return null;
}
}
return { id, text: parts.join("\n") };
} catch (e) {
if (!current()) return null;
notifications().notify({
level: "error",
title: "Cannot generate the DDL",
body: e instanceof Error ? e.message : String(e),
});
return null;
}
}
/** SQL Scripts › Select / Insert / Update / Delete templates into the console. */
export async function insertScript(n: DbNode, kind: ScriptKind) {
const t = tableOf(n);
if (!t) return;
const current = databaseRequest(t.id);
const key = detailsKey(t.id, t.schema, t.table);
if (useDatabase.getState().details[key]?.status !== "ok") await loadDetails(t.id, t.schema, t.table);
if (!current()) return;
const d = useDatabase.getState().details[key];
const columns = d?.status === "ok" ? d.value.columns : [];
try {
await openConsoleWith(t.id, scriptSql(driverOf(t.id), kind, t.schema, t.table, columns));
} catch (e) {
notifications().notify({
level: "error",
title: "Cannot generate the SQL script",
body: e instanceof Error ? e.message : String(e),
});
}
}
/** SQL Scripts › Run SQL Script…: picks a `.sql` file and runs all its statements. */
async function runScriptFile(id: string) {
const { open } = await import("@/platform/dialog");
const file = await open({
multiple: false,
directory: false,
title: "Run SQL Script",
filters: [{ name: "SQL", extensions: ["sql", "ddl"] }],
});
if (typeof file !== "string") return;
try {
const text = await readDesktopText(file);
const statements = await call(commands.dbStatements(id, text, 0, text.length));
useDatabase.setState({ activeResult: OUTPUT_TAB });
showServiceView(RESULTS_VIEW, false);
if (
await runSql(
id,
statements.map((s) => s.text),
)
)
notifications().notify({
level: "info",
title: `Script finished: ${statements.length} statement${statements.length === 1 ? "" : "s"}`,
});
} catch (e) {
notifications().notify({
level: "error",
title: "Cannot run the script",
body: e instanceof Error ? e.message : String(e),
});
}
}
function refreshNode(n: DbNode | null) {
if (!n) {
void loadSources();
for (const c of useDatabase.getState().connected) void refresh(c);
return;
}
if (n.kind === "sourceFolder") {
for (const id of n.folder.sources) void refresh(id);
return;
}
const id = nodeTarget(n);
if (!id) return;
if (n.kind === "schema" || n.kind === "folder") void loadTables(id, n.schema, n.catalog);
else if (tableOf(n)) {
const t = tableOf(n)!;
void loadDetails(t.id, t.schema, t.table, t.catalog);
} else void refresh(id);
}
export function registerDatabaseTreeActions(): () => void {
const tree = (a: Omit<Action, "category">): Action => ({
category: "Database",
when: OPEN,
keyWhen: DB_VIEW_FOCUS,
...a,
});
return registerActions([
tree({
id: "db.properties",
title: "Data Source Properties…",
icon: "db-properties",
keywords: ["data sources", "connection settings"],
run: ({ arg }) => {
const node = nodeFrom(arg);
if (node?.kind === "sourceFolder") return;
const src = sourceOf(node);
const { sources } = useDatabase.getState();
openSourceDialog(src ?? (sources.length === 1 ? sources[0]! : null));
},
}),
tree({
id: "db.refresh",
title: "Refresh",
icon: "refresh",
keywords: ["synchronize", "introspect"],
run: ({ arg }) => {
const sources = sourcesFrom(arg);
if (sources.length > 1) return void refreshSources(sources);
refreshNode(nodeFrom(arg));
},
}),
tree({
id: "db.introspect",
title: "Introspect All Databases",
icon: "refresh",
keywords: ["snowflake", "completion", "catalog", "schemas"],
run: ({ arg }) => {
const n = nodeFrom(arg);
const id = n ? nodeTarget(n) : null;
if (id) void introspectSource(id);
},
}),
tree({
id: "db.disconnect",
title: "Deactivate",
icon: "db-disconnect",
keywords: ["disconnect", "close connection"],
run: ({ arg }) => {
const sources = sourcesFrom(arg);
if (sources.length > 1) return void deactivateSources(sources);
const n = nodeFrom(arg);
const id = n ? nodeTarget(n) : null;
if (!id) {
for (const c of useDatabase.getState().connected) void disconnect(c);
return;
}
// A database node closes its own connection; anything else the data source's.
void disconnect(n?.kind === "database" ? id : splitTarget(id).id);
},
}),
tree({
id: "db.jumpToConsole",
title: "Jump to Query Console…",
icon: "db-console",
run: ({ arg }) => {
const n = nodeFrom(arg);
const id = n ? nodeTarget(n) : null;
const { sources } = useDatabase.getState();
const target = id ?? (sources.length === 1 ? (sources[0]!.id ?? null) : null);
if (target) void jumpToConsole(target);
else toolWindowService().show(DB_TOOL_WINDOW, true);
},
}),
tree({
id: "db.editData",
title: "Edit Data",
icon: "db-table",
keywords: ["open table", "table editor"],
run: ({ arg }) => {
const n = nodeFrom(arg);
const t = n && tableOf(n);
if (t) openTableData(t.id, t.schema, t.table, t.catalog);
},
}),
tree({
id: "db.goToDdl",
title: "Go to DDL",
icon: "file-sql",
keywords: ["edit source", "definition", "create table"],
run: ({ arg }) => {
const n = nodeFrom(arg);
const o = n && schemaObjectOf(n);
if (o) return void openObjectDdl(o.id, o.schema, o.kind, o.name);
const t = n && tableOf(n);
if (t && t.catalog === undefined) void openDdl(t.id, t.schema, t.table);
},
}),
tree({
id: "db.quickDoc",
title: "Quick Documentation",
icon: "info",
run: ({ arg }) => {
const n = nodeFrom(arg);
if (n && n.kind !== "message" && n.kind !== "sourceFolder")
openDialog({ kind: "quickDoc", node: n, anchor: rowAnchor() });
},
}),
tree({
id: "db.rename",
title: "Rename…",
icon: "edit",
run: ({ arg }) => {
const n = nodeFrom(arg);
if (!n) return;
if (n.kind === "sourceFolder") return openDialog({ kind: "sourceFolder", folder: n.folder });
const id = nodeTarget(n);
if (n.kind === "source" && id) return openDialog({ kind: "rename", id, object: null });
const source = sourceById(id);
if (n.kind === "database" && !n.current && !source?.readOnly && createsDatabases(source))
return openDialog({ kind: "renameDatabase", id: splitTarget(n.id).id, database: n.name });
const o = objectOf(n);
if (id && o && canRename(driverOf(id), o)) openDialog({ kind: "rename", id, object: o });
},
}),
tree({
id: "db.drop",
title: "Drop…",
icon: "trash",
keywords: ["delete", "remove data source"],
run: ({ arg }) => {
const sources = sourcesFrom(arg);
if (sources.length > 1) return void removeSources(sources.map((source) => source.source));
const n = nodeFrom(arg);
if (!n) return;
if (n.kind === "sourceFolder") return void removeSourceFolder(n.folder);
const id = nodeTarget(n);
if (n.kind === "source") return void removeSources([n.source]);
const source = sourceById(id);
if (n.kind === "database" && !n.current && !source?.readOnly && createsDatabases(source))
return openDialog({ kind: "dropDatabase", id: splitTarget(n.id).id, database: n.name });
const o = objectOf(n);
if (id && o && canDrop(driverOf(id), o)) openDialog({ kind: "drop", id, object: o });
},
}),
tree({
id: "db.truncate",
title: "Truncate…",
keywords: ["delete all rows", "empty table"],
run: ({ arg }) => {
const n = nodeFrom(arg);
if (n?.kind === "table" && n.table.kind === "table" && driverOf(n.id) !== "jdbc")
openDialog({ kind: "truncate", id: n.id, schema: n.schema, table: n.table.name });
},
}),
tree({
id: "db.modifyTable",
title: "Modify Table…",
icon: "edit",
keywords: ["alter table", "add column", "modify column"],
run: ({ arg }) => {
const n = nodeFrom(arg);
const t = n && tableOf(n);
if (!t || t.view || !canModifyTable(driverOf(t.id))) return;
openDialog({
kind: "modifyTable",
id: t.id,
schema: t.schema,
table: t.table,
focusColumn: n.kind === "column" ? n.column.name : undefined,
});
},
}),
tree({
id: "db.newDatabase",
title: "Database…",
icon: "db-database",
keywords: ["create database", "new database"],
run: ({ arg }) => {
const source = sourceOf(nodeFrom(arg));
if (source?.id && !source.readOnly && createsDatabases(source))
openDialog({ kind: "createDatabase", id: source.id });
},
}),
tree({
id: "db.newSchema",
title: "Schema…",
icon: "db-schema",
keywords: ["create schema", "new schema"],
run: ({ arg }) => {
const n = nodeFrom(arg);
const id = n && newSchemaTarget(n);
if (id && !sourceById(id)?.readOnly) openDialog({ kind: "createSchema", id });
},
}),
tree({
id: "db.newTable",
title: "Table",
icon: "db-table",
keywords: ["create table", "new table"],
run: ({ arg }) => {
const n = nodeFrom(arg);
const id = n && nodeTarget(n);
if (!n || !id || driverOf(id) === "jdbc") return;
const schema =
"schema" in n && typeof n.schema === "string" ? n.schema : driverOf(id) === "sqlite" ? "main" : null;
if (schema !== null) openDialog({ kind: "modifyTable", id, schema, table: null });
},
}),
tree({
id: "db.compareSchemas",
title: "Compare Structure…",
description: "Compare the tables of two schemas and write the migration SQL from one to the other",
icon: "diff-side-by-side",
keywords: ["schema compare", "diff", "migration", "compare schemas", "structure"],
run: ({ arg }) => {
const n = nodeFrom(arg);
const id = n && nodeTarget(n);
const schema = n && "schema" in n && typeof n.schema === "string" ? n.schema : null;
if (id && driverOf(id) === "jdbc") return;
openDialog({
kind: "compareSchemas",
source: id ? { id, schema: schema ?? (driverOf(id) === "sqlite" ? "main" : "") } : null,
});
},
}),
tree({
id: "db.newColumn",
title: "Column",
icon: "db-column",
keywords: ["add column"],
run: ({ arg }) => {
const n = nodeFrom(arg);
const t = n && tableOf(n);
if (t && !t.view && canModifyTable(driverOf(t.id)))
openDialog({ kind: "modifyTable", id: t.id, schema: t.schema, table: t.table, addColumn: true });
},
}),
tree({
id: "db.importData",
title: "Import Data from File…",
icon: "import",
keywords: ["csv", "tsv", "load data"],
run: ({ arg }) => {
const n = nodeFrom(arg);
if (
n?.kind === "table" &&
n.table.kind === "table" &&
driverOf(n.id) !== "clickhouse" &&
driverOf(n.id) !== "jdbc"
)
openDialog({ kind: "import", id: n.id, schema: n.schema, table: n.table.name });
},
}),
tree({
id: "db.dumpWithPgDump",
title: "Export with 'pg_dump'…",
icon: "export",
keywords: ["backup", "dump", "postgresql"],
run: async ({ arg }) => {
const n = nodeFrom(arg);
const scope = n && dumpScope(n, sourceOf(n));
const serverVersion = scope && (await serverVersionOf(scope.target));
if (scope && serverVersion !== undefined) openDialog({ kind: "dump", ...scope, serverVersion });
},
}),
tree({
id: "db.restoreWithPgRestore",
title: "Restore with 'pg_restore'/'psql'…",
icon: "download",
keywords: ["backup", "restore", "load dump", "postgresql"],
run: async ({ arg }) => {
const n = nodeFrom(arg);
const scope = n && dumpScope(n, sourceOf(n));
const serverVersion = scope && (await serverVersionOf(scope.target));
if (scope && serverVersion !== undefined)
openDialog({ kind: "restore", target: scope.target, database: scope.database, serverVersion });
},
}),
tree({
id: "db.dumpWithMysqldump",
title: "Export with 'mysqldump'…",
icon: "export",
keywords: ["backup", "dump", "mysql", "mariadb"],
run: async ({ arg }) => {
const n = nodeFrom(arg);
const scope = n && mysqlDumpScope(n, sourceOf(n));
if (scope && (await connect(scope.target))) openDialog({ kind: "mysqlDump", ...scope });
},
}),
tree({
id: "db.restoreWithMysql",
title: "Restore with 'mysql'…",
icon: "download",
keywords: ["backup", "restore", "load dump", "mysql", "mariadb"],
run: async ({ arg }) => {
const n = nodeFrom(arg);
const scope = n && mysqlDumpScope(n, sourceOf(n));
if (scope && (await connect(scope.target)))
openDialog({ kind: "mysqlRestore", target: scope.target, database: scope.database });
},
}),
tree({
id: "db.copyReference",
title: "Copy Reference",
icon: "copy",
keywords: ["qualified name"],
run: ({ arg }) => {
const n = nodeFrom(arg);
if (!n) return;
const id = nodeTarget(n);
if (n.kind === "source") return void copy(n.source.name ?? "", tx("Cannot copy the name"));
if (n.kind === "database") return void copy(n.name, tx("Cannot copy the name"));
const o = objectOf(n);
if (!id || !o) return;
if ("catalog" in n && n.catalog !== undefined) {
const parts = n.kind === "schema" ? [n.catalog, n.schema] : [n.catalog, o.schema, o.name];
if (n.kind === "column") parts.push(n.column.name);
return void copy(parts.map((name) => quoteIdent("jdbc", name)).join("."), tx("Cannot copy the reference"));
}
void copy(reference(driverOf(id), o), tx("Cannot copy the reference"));
},
}),
tree({
id: "db.duplicateSource",
title: "Duplicate",
icon: "copy",
keywords: ["copy data source"],
run: ({ arg }) => {
const src = sourceOf(nodeFrom(arg));
if (src?.id) void duplicateSource(src.id);
},
}),
tree({
id: "db.ddlToClipboard",
title: "Generate DDL to Clipboard",
icon: "copy",
keywords: ["create table", "sql script"],
run: async ({ arg }) => {
const n = nodeFrom(arg);
const ddl = n && (await ddlOf(n));
if (ddl) await copy(ddl.text, tx("Cannot copy the DDL"));
},
}),
tree({
id: "db.ddlToConsole",
title: "Generate DDL to Query Console",
icon: "db-console",
keywords: ["create table", "sql script"],
run: async ({ arg }) => {
const n = nodeFrom(arg);
const ddl = n && (await ddlOf(n));
if (ddl) await openConsoleWith(ddl.id, ddl.text);
},
}),
tree({
id: "db.runSqlScript",
title: "Run SQL Script…",
icon: "run",
keywords: ["execute file", "import sql"],
run: ({ arg }) => {
const n = nodeFrom(arg);
const { sources } = useDatabase.getState();
const id = (n && nodeTarget(n)) ?? (sources.length === 1 ? sources[0]!.id : null);
if (id) void runScriptFile(id);
},
}),
tree({
id: "db.sqlScript",
title: "SQL Script Template",
hidden: true,
run: ({ arg }) => {
const a = (arg ?? {}) as { node?: DbNode; kind?: ScriptKind };
const n = a.node ?? useDatabase.getState().selectedNode;
if (n && a.kind) void insertScript(n, a.kind);
},
}),
tree({
id: "db.goToReferencedTable",
title: "Go to Referenced Table",
keywords: ["foreign key"],
run: ({ arg }) => {
const n = nodeFrom(arg);
if (n?.kind === "foreignKey") void revealInTree(n.id, n.fk.refSchema, n.fk.refTable, "table");
},
}),
tree({
id: "db.showDiagram",
title: "Show Diagram",
description: "Show the selected tables, or the tables of a schema, as an ER diagram linked by foreign keys",
icon: "db-table",
keywords: ["er diagram", "uml", "visualization", "foreign keys", "relationships"],
run: ({ arg }) => showDiagram(nodesFrom(arg), false),
}),
tree({
id: "db.showDiagramPopup",
title: "Show Diagram Popup",
description: "Show the ER diagram of the selected tables in a popup",
icon: "db-table",
keywords: ["er diagram", "uml", "visualization", "foreign keys", "relationships"],
run: ({ arg }) => showDiagram(nodesFrom(arg), true),
}),
tree({
id: "db.new",
title: "New…",
icon: "plus",
keywords: ["query console", "data source"],
run: () => {
toolWindowService().show(DB_TOOL_WINDOW, false);
useDatabase.setState({ newMenuOpen: true });
},
}),
tree({
id: "db.newSourceFolder",
title: "New Data Source Folder…",
icon: "folder",
run: ({ arg }) =>
openDialog({
kind: "sourceFolder",
folder: null,
sources: sourceIdsFrom(arg),
}),
}),
tree({
id: "db.renameSourceFolder",
title: "Rename Data Source Folder…",
icon: "edit",
run: ({ arg }) => {
const node = nodeFrom(arg);
if (node?.kind === "sourceFolder") openDialog({ kind: "sourceFolder", folder: node.folder });
},
}),
tree({
id: "db.deleteSourceFolder",
title: "Delete Data Source Folder…",
icon: "trash",
run: ({ arg }) => {
const node = nodeFrom(arg);
if (node?.kind === "sourceFolder") void removeSourceFolder(node.folder);
},
}),
tree({
id: "db.separateProceduresAndFunctions",
title: "Separate Procedures and Functions",
run: toggleSeparateProceduresAndFunctions,
}),
tree({
id: "db.showTableComments",
title: "Show Table Comments",
run: toggleShowTableComments,
}),
tree({
id: "db.selectOpened",
title: "Select Opened File",
icon: "locate",
keywords: ["locate", "scroll from editor", "scroll from source", "select in database view"],
// From the editor: a user-assigned shortcut works outside the Database view too.
keyWhen: undefined,
run: () => void revealOpened(),
}),
tree({
id: "db.expandAll",
title: "Expand All",
icon: "expand-all",
run: () => databaseTree.expandAll?.(),
}),
tree({
id: "db.collapseAll",
title: "Collapse All",
icon: "collapse-all",
run: () => useDatabase.setState({ treeExpanded: new Set() }),
}),
]);
}
/** One console opens directly; with several, DataGrip's list of them plus New Query Console. */
async function jumpToConsole(id: string): Promise<void> {
const files = await consoleFiles(id).catch(() => []);
if (files.length <= 1) return openConsole(id);
const names = files.map((f) => (f.split(/[\\/]/).pop() ?? f).replace(/\.sql$/, ""));
const create = tx("New Query Console");
const picked = await chooseItem({ title: "Query Consoles", items: [...names, create] });
if (picked === create) await newConsole(id);
else if (picked) await openConsoleFile(id, files[names.indexOf(picked)]!);
}