дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 01:31:41 +02:00
- Introspected tree folder labels (tables, views, routines, keys, …) are localized. - Database/schema introspection pickers get Select all filtered. - New › Data Source lists recently added data source types in a Recent section first, seeded from existing sources on first use. - New PostgreSQL data sources default to the postgres database. - Modify Table is resizable, its content following the window size. Co-authored-by: wangyuewen-china <[email protected]>
896 рядки
34 KiB
TypeScript
896 рядки
34 KiB
TypeScript
/**
|
||
* Database tool window (IDEA's layout): data source → database (PostgreSQL) → schema → `tables` /
|
||
* `views` / `materialized views` / `routines` (optionally `procedures` / `functions`) / `packages` /
|
||
* `sequences` folders → table → `columns` / `keys` / `foreign keys` / `indexes` / `triggers`,
|
||
* with counts and column types, loaded lazily. Double-click a table to open its data, a data
|
||
* source to open its query console.
|
||
*/
|
||
import { useEffect, useMemo, useRef, useState } from "react";
|
||
import type { DbDatabases, DbTableDetails } from "@/platform/ipc";
|
||
import { executeAction } from "@/platform/actions";
|
||
import { shortcutLabel } from "@/platform/keymap";
|
||
import {
|
||
Button,
|
||
EmptyState,
|
||
HighlightedText,
|
||
Icon,
|
||
IconButton,
|
||
Menu,
|
||
registerDropTarget,
|
||
Toolbar,
|
||
Tree,
|
||
showContextMenu,
|
||
tooltipAttrs,
|
||
type TreeHandle,
|
||
T,
|
||
} from "@/ui";
|
||
import {
|
||
databaseKey,
|
||
passesObjectFilter,
|
||
schemaNodeKey,
|
||
shownNames,
|
||
sourceIcon,
|
||
splitTarget,
|
||
targetOf,
|
||
treeIdentifier,
|
||
} from "./model";
|
||
import { IntrospectionPicker } from "./IntrospectionPicker";
|
||
import {
|
||
nodeTarget,
|
||
isOtherFolder,
|
||
otherFolder,
|
||
routineFolder,
|
||
schemaObjectOf,
|
||
tableFolder,
|
||
type DbNode as Node,
|
||
type Folder,
|
||
type Group,
|
||
} from "./nodes";
|
||
import {
|
||
connect,
|
||
detailsKey,
|
||
duckdbCatalogTree,
|
||
listsTreeDatabases,
|
||
loadDatabases,
|
||
loadDetails,
|
||
loadSchemas,
|
||
loadSources,
|
||
loadSourceFolders,
|
||
loadTables,
|
||
moveSourcesToFolder,
|
||
openConsole,
|
||
openObjectDdl,
|
||
saveSourceVisibility,
|
||
schemasKey,
|
||
tablesKey,
|
||
useDatabase,
|
||
type Loaded,
|
||
} from "./store";
|
||
import { DB_VIEW_FOCUS, databaseTree, openTableData } from "./treeActions";
|
||
import { newMenu, nodeMenu } from "./treeMenu";
|
||
import styles from "./Database.module.css";
|
||
import { formatMessage, tx, useTx } from "@/platform/i18n";
|
||
import { databaseRequest } from "./requests";
|
||
|
||
const GROUP_LABELS: Record<Group, string> = {
|
||
columns: "columns",
|
||
keys: "keys",
|
||
foreignKeys: "foreign keys",
|
||
indexes: "indexes",
|
||
triggers: "triggers",
|
||
};
|
||
|
||
const FOLDER_LABELS: Record<Folder, string> = {
|
||
tables: "tables",
|
||
views: "views",
|
||
materializedViews: "materialized views",
|
||
routines: "routines",
|
||
procedures: "procedures",
|
||
functions: "functions",
|
||
packages: "packages",
|
||
sequences: "sequences",
|
||
stages: "stages",
|
||
streams: "streams",
|
||
tasks: "tasks",
|
||
pipes: "pipes",
|
||
fileFormats: "file formats",
|
||
};
|
||
|
||
const OTHERS: readonly Folder[] = ["stages", "streams", "tasks", "pipes", "fileFormats"];
|
||
const FOLDERS: readonly Folder[] = [
|
||
"tables",
|
||
"views",
|
||
"materializedViews",
|
||
"routines",
|
||
"packages",
|
||
"sequences",
|
||
...OTHERS,
|
||
];
|
||
const SEPARATE_FOLDERS: readonly Folder[] = [
|
||
"tables",
|
||
"views",
|
||
"materializedViews",
|
||
"procedures",
|
||
"functions",
|
||
"packages",
|
||
"sequences",
|
||
...OTHERS,
|
||
];
|
||
const SOURCE_DRAG = "application/x-openidea-db-sources";
|
||
|
||
function status<T>(key: string, l: Loaded<T> | undefined, map: (v: T) => Node[]): Node[] | undefined {
|
||
if (!l) return undefined;
|
||
if (l.status === "loading") return undefined;
|
||
if (l.status === "error") return [{ kind: "message", key: `${key}/err`, text: l.message, error: true }];
|
||
const nodes = map(l.value);
|
||
return nodes.length ? nodes : [{ kind: "message", key: `${key}/empty`, text: "Empty" }];
|
||
}
|
||
|
||
const primaryKey = (d: DbTableDetails) => d.columns.filter((c) => c.primaryKey).map((c) => c.name);
|
||
|
||
/** Rows under a table: IDEA's columns / keys / foreign keys / indexes folders (empty ones left out). */
|
||
function groupsOf(d: DbTableDetails): Group[] {
|
||
const g: Group[] = ["columns"];
|
||
if (primaryKey(d).length) g.push("keys");
|
||
if (d.foreignKeys.length) g.push("foreignKeys");
|
||
if (d.indexes.length) g.push("indexes");
|
||
if (d.triggers.length) g.push("triggers");
|
||
return g;
|
||
}
|
||
|
||
function groupSize(d: DbTableDetails, g: Group): number {
|
||
if (g === "columns") return d.columns.length;
|
||
if (g === "keys") return primaryKey(d).length ? 1 : 0;
|
||
if (g === "foreignKeys") return d.foreignKeys.length;
|
||
if (g === "triggers") return d.triggers.length;
|
||
return d.indexes.length;
|
||
}
|
||
|
||
export function DatabaseView() {
|
||
const t = useTx();
|
||
const st = useDatabase();
|
||
const folders = st.separateProceduresAndFunctions ? SEPARATE_FOLDERS : FOLDERS;
|
||
const tree = useRef<TreeHandle>(null);
|
||
const treeHost = useRef<HTMLDivElement>(null);
|
||
const [dropFolder, setDropFolder] = useState<string | null>(null);
|
||
useEffect(() => {
|
||
if (!st.loaded) void loadSources();
|
||
}, [st.loaded]);
|
||
useEffect(() => {
|
||
if (!st.foldersLoaded) void loadSourceFolders();
|
||
}, [st.foldersLoaded]);
|
||
useEffect(() => {
|
||
const host = treeHost.current;
|
||
if (!host) return;
|
||
const folderAt = (x: number, y: number) => {
|
||
const key = document.elementFromPoint(x, y)?.closest<HTMLElement>("[data-tree-key]")?.dataset.treeKey;
|
||
return key?.startsWith("source-folder:")
|
||
? useDatabase.getState().folders.find((folder) => key === `source-folder:${folder.id}`)
|
||
: undefined;
|
||
};
|
||
return registerDropTarget(host, {
|
||
accepts: (type) => type === SOURCE_DRAG,
|
||
over: (_data, x, y) => setDropFolder(folderAt(x, y)?.id ?? null),
|
||
leave: () => setDropFolder(null),
|
||
drop: (data, x, y) => {
|
||
const folder = folderAt(x, y);
|
||
setDropFolder(null);
|
||
if (!folder) return;
|
||
try {
|
||
const sources = JSON.parse(data.payload) as unknown;
|
||
if (Array.isArray(sources) && sources.every((source) => typeof source === "string"))
|
||
void moveSourcesToFolder(sources, folder.id);
|
||
} catch {
|
||
// A malformed payload can only come from this view; ignore it.
|
||
}
|
||
},
|
||
});
|
||
}, [st.folders.length, st.sources.length]);
|
||
// Go to Declaration from a console, Select Opened File: the rows exist once the expanded nodes render.
|
||
useEffect(() => {
|
||
if (!st.treeReveal) return;
|
||
const path = st.treeReveal.path;
|
||
const frame = requestAnimationFrame(() => {
|
||
// Spread + reverse instead of toReversed(), which needs Safari 16.4 (the floor is 15.4).
|
||
[...path].reverse().some((key) => tree.current?.reveal(key));
|
||
tree.current?.focus();
|
||
});
|
||
return () => cancelAnimationFrame(frame);
|
||
}, [st.treeReveal]);
|
||
|
||
const roots = useMemo<Node[]>(() => {
|
||
const grouped = new Set(st.folders.flatMap((folder) => folder.sources));
|
||
return [
|
||
...[...st.folders]
|
||
.sort((a, b) => a.order - b.order || a.name.localeCompare(b.name))
|
||
.map((folder): Node => ({ kind: "sourceFolder", key: `source-folder:${folder.id}`, folder })),
|
||
...st.sources
|
||
.filter((source) => !grouped.has(source.id ?? ""))
|
||
.map((source): Node => ({ kind: "source", key: source.id ?? "", source })),
|
||
{ kind: "workspace", key: ":query-workspace" },
|
||
];
|
||
}, [st.folders, st.sources]);
|
||
|
||
/** Schemas tab › Object filter of the data source of target `id`. */
|
||
const shown = (id: string) => {
|
||
const filter = sourceOf(id)?.introspection?.objectFilter;
|
||
return (o: { name: string }) => passesObjectFilter(o.name, filter);
|
||
};
|
||
const tablesOf = (id: string, schema: string, catalog?: string) => {
|
||
const t = st.tables[tablesKey(id, schema, catalog)];
|
||
return t?.status === "ok" ? t.value.filter(shown(id)) : null;
|
||
};
|
||
const routinesOf = (id: string, schema: string) =>
|
||
(st.objects[tablesKey(id, schema)]?.routines ?? []).filter(shown(id));
|
||
const sequencesOf = (id: string, schema: string) =>
|
||
(st.objects[tablesKey(id, schema)]?.sequences ?? []).filter(shown(id));
|
||
const packagesOf = (id: string, schema: string) =>
|
||
(st.objects[tablesKey(id, schema)]?.packages ?? []).filter(shown(id));
|
||
const othersOf = (id: string, schema: string, folder: Folder) =>
|
||
(st.objects[tablesKey(id, schema)]?.others ?? []).filter((o) => otherFolder(o.kind) === folder).filter(shown(id));
|
||
/** Members of a schema folder, after object filtering. */
|
||
const folderSize = (id: string, schema: string, folder: Folder, catalog?: string): number => {
|
||
if (catalog !== undefined)
|
||
return (tablesOf(id, schema, catalog) ?? []).filter((t) => tableFolder(t.kind) === folder).length;
|
||
if (isOtherFolder(folder)) return othersOf(id, schema, folder).length;
|
||
if (folder === "routines" || folder === "procedures" || folder === "functions")
|
||
return routinesOf(id, schema).filter(
|
||
(routine) => routineFolder(routine.kind, st.separateProceduresAndFunctions) === folder,
|
||
).length;
|
||
if (folder === "packages") return packagesOf(id, schema).length;
|
||
if (folder === "sequences") return sequencesOf(id, schema).length;
|
||
return (tablesOf(id, schema) ?? []).filter((t) => tableFolder(t.kind) === folder).length;
|
||
};
|
||
const detailsOf = (id: string, schema: string, table: string, catalog?: string) => {
|
||
const d = st.details[detailsKey(id, schema, table, catalog)];
|
||
return d?.status === "ok" ? d.value : null;
|
||
};
|
||
|
||
const sourceOf = (target: string) => st.sources.find((s) => s.id === splitTarget(target).id);
|
||
const schemaOverride = (target: string, database: string | null) => {
|
||
const overrides = sourceOf(target)?.introspection?.schemasByDatabase;
|
||
return database !== null && overrides && Object.hasOwn(overrides, database) ? overrides[database] : undefined;
|
||
};
|
||
const defaultSchemas = (target: string, names: string[]) => {
|
||
const i = sourceOf(target)?.introspection;
|
||
return shownNames(names, i?.allSchemas, i?.schemas);
|
||
};
|
||
const exactNames = (available: string[], choice: readonly string[]) => {
|
||
const picked = new Set(choice);
|
||
return available.filter((name) => picked.has(name));
|
||
};
|
||
const shownSchemas = (target: string, names: string[], database: string | null) => {
|
||
const override = schemaOverride(target, database);
|
||
if (!override) return defaultSchemas(target, names);
|
||
return override.all ? names : exactNames(names, override.names ?? []);
|
||
};
|
||
const shownDatabases = (id: string, v: DbDatabases) => {
|
||
const i = sourceOf(id)?.introspection;
|
||
return shownNames(v.names, i?.allDatabases, i?.databases, v.current);
|
||
};
|
||
|
||
const schemasOf = (key: string, id: string, database: string | null, catalog?: string) =>
|
||
status(key, st.schemas[schemasKey(id, catalog)], (v) =>
|
||
shownSchemas(id, v, database).map((schema): Node => ({
|
||
kind: "schema",
|
||
key: schemaNodeKey(id, schema, catalog),
|
||
id,
|
||
schema,
|
||
catalog,
|
||
})),
|
||
);
|
||
|
||
const children = (n: Node): readonly Node[] | undefined => {
|
||
switch (n.kind) {
|
||
case "sourceFolder":
|
||
return n.folder.sources.flatMap((id) => {
|
||
const source = st.sources.find((candidate) => candidate.id === id);
|
||
return source ? [{ kind: "source" as const, key: source.id ?? "", source }] : [];
|
||
});
|
||
case "source": {
|
||
const id = n.source.id ?? "";
|
||
if (listsTreeDatabases(n.source)) {
|
||
const duckdb = duckdbCatalogTree(n.source);
|
||
return status(n.key, st.databases[id], (v) =>
|
||
shownDatabases(id, v).map((name) => ({
|
||
kind: "database",
|
||
key: databaseKey(id, name, duckdb),
|
||
id: duckdb ? id : targetOf(id, name, v.current),
|
||
name,
|
||
current: name === v.current,
|
||
catalog: duckdb ? name : undefined,
|
||
})),
|
||
);
|
||
}
|
||
return schemasOf(n.key, id, null);
|
||
}
|
||
case "database":
|
||
return schemasOf(n.key, n.id, n.name, n.catalog);
|
||
case "schema":
|
||
return status(n.key, st.tables[tablesKey(n.id, n.schema, n.catalog)], () =>
|
||
folders
|
||
.filter((f) => folderSize(n.id, n.schema, f, n.catalog) > 0)
|
||
.map((folder): Node => ({
|
||
kind: "folder",
|
||
key: `${n.key}/${folder}`,
|
||
id: n.id,
|
||
schema: n.schema,
|
||
catalog: n.catalog,
|
||
folder,
|
||
})),
|
||
);
|
||
case "folder": {
|
||
const at = { id: n.id, schema: n.schema, catalog: n.catalog };
|
||
if (n.folder === "routines" || n.folder === "procedures" || n.folder === "functions")
|
||
// Overloads share a name: the key tells them apart by their arguments.
|
||
return routinesOf(n.id, n.schema)
|
||
.filter((routine) => routineFolder(routine.kind, st.separateProceduresAndFunctions) === n.folder)
|
||
.map((routine) => ({
|
||
kind: "routine",
|
||
key: `${n.key}/${routine.name}(${routine.arguments})`,
|
||
routine,
|
||
...at,
|
||
}));
|
||
if (n.folder === "packages")
|
||
return packagesOf(n.id, n.schema).map((pkg) => ({
|
||
kind: "package" as const,
|
||
key: `${n.key}/${pkg.name}`,
|
||
package: pkg,
|
||
...at,
|
||
}));
|
||
if (isOtherFolder(n.folder))
|
||
return othersOf(n.id, n.schema, n.folder).map((object) => ({
|
||
kind: "object",
|
||
key: `${n.key}/${object.name}`,
|
||
object,
|
||
...at,
|
||
}));
|
||
if (n.folder === "sequences")
|
||
return sequencesOf(n.id, n.schema).map((sequence) => ({
|
||
kind: "sequence",
|
||
key: `${n.key}/${sequence.name}`,
|
||
sequence,
|
||
...at,
|
||
}));
|
||
return (tablesOf(n.id, n.schema, n.catalog) ?? [])
|
||
.filter((t) => tableFolder(t.kind) === n.folder)
|
||
.map((table) => ({ kind: "table", key: `${n.key}/${treeIdentifier(table.name, n.catalog)}`, table, ...at }));
|
||
}
|
||
case "table": {
|
||
const d = st.details[detailsKey(n.id, n.schema, n.table.name, n.catalog)];
|
||
if (!d || d.status === "loading") return undefined;
|
||
if (d.status === "error") return [{ kind: "message", key: `${n.key}/err`, text: d.message, error: true }];
|
||
return groupsOf(d.value).map((group) => ({
|
||
kind: "group",
|
||
key: `${n.key}/${group}`,
|
||
id: n.id,
|
||
schema: n.schema,
|
||
table: n.table.name,
|
||
catalog: n.catalog,
|
||
group,
|
||
}));
|
||
}
|
||
case "group": {
|
||
const d = detailsOf(n.id, n.schema, n.table, n.catalog);
|
||
if (!d) return undefined;
|
||
const fkCols = new Set(d.foreignKeys.flatMap((k) => k.columns));
|
||
const at = { id: n.id, schema: n.schema, table: n.table, catalog: n.catalog };
|
||
switch (n.group) {
|
||
case "columns":
|
||
return d.columns.map((column) => ({
|
||
kind: "column",
|
||
key: `${n.key}/${treeIdentifier(column.name, n.catalog)}`,
|
||
column,
|
||
foreignKey: fkCols.has(column.name),
|
||
...at,
|
||
}));
|
||
case "keys":
|
||
return [{ kind: "key", key: `${n.key}/pk`, columns: primaryKey(d), ...at }];
|
||
case "foreignKeys":
|
||
return d.foreignKeys.map((fk, i) => ({ kind: "foreignKey", key: `${n.key}/${i}`, fk, ...at }));
|
||
case "indexes":
|
||
return d.indexes.map((index) => ({ kind: "index", key: `${n.key}/${index.name}`, index, ...at }));
|
||
case "triggers":
|
||
return d.triggers.map((trigger) => ({ kind: "trigger", key: `${n.key}/${trigger.name}`, trigger, ...at }));
|
||
}
|
||
return undefined;
|
||
}
|
||
default:
|
||
return undefined;
|
||
}
|
||
};
|
||
|
||
const load = async (n: Node) => {
|
||
if (n.kind === "source") {
|
||
const id = n.source.id ?? "";
|
||
const current = databaseRequest(id);
|
||
const connected = await connect(id);
|
||
if (!current()) return;
|
||
if (!connected) {
|
||
const err = { status: "error" as const, message: tx("Cannot connect") };
|
||
if (listsTreeDatabases(n.source)) useDatabase.setState((s) => ({ databases: { ...s.databases, [id]: err } }));
|
||
else useDatabase.setState((s) => ({ schemas: { ...s.schemas, [id]: err } }));
|
||
return;
|
||
}
|
||
if (listsTreeDatabases(n.source)) await loadDatabases(id);
|
||
else await loadSchemas(id);
|
||
} else if (n.kind === "database") {
|
||
const current = databaseRequest(n.id);
|
||
const connected = await connect(n.id);
|
||
if (!current()) return;
|
||
if (!connected) {
|
||
useDatabase.setState((s) => ({
|
||
schemas: { ...s.schemas, [schemasKey(n.id, n.catalog)]: { status: "error", message: tx("Cannot connect") } },
|
||
}));
|
||
return;
|
||
}
|
||
await loadSchemas(n.id, n.catalog);
|
||
} else if (n.kind === "schema") await loadTables(n.id, n.schema, n.catalog);
|
||
else if (n.kind === "table") await loadDetails(n.id, n.schema, n.table.name, n.catalog);
|
||
};
|
||
|
||
const picker = (n: Node, lead: boolean) => {
|
||
if (n.kind !== "source" && n.kind !== "database") return null;
|
||
const source = n.kind === "source" ? n.source : sourceOf(n.id);
|
||
if (!source?.id || source.driver === "sqlite") return null;
|
||
const sourceId = source.id;
|
||
const database = n.kind === "database" ? n.name : null;
|
||
const target = n.kind === "database" ? n.id : sourceId;
|
||
const listDatabases = database === null && listsTreeDatabases(source);
|
||
const databases = listDatabases ? st.databases[sourceId] : undefined;
|
||
const schemas = listDatabases
|
||
? undefined
|
||
: st.schemas[schemasKey(target, n.kind === "database" ? n.catalog : undefined)];
|
||
const intro = source.introspection;
|
||
const name = label(n);
|
||
const kind =
|
||
listDatabases || source.driver === "clickhouse" || source.vendor === "clickhouse" ? "databases" : "schemas";
|
||
const title = kind === "databases" ? tx("Choose databases for {name}") : tx("Choose schemas for {name}");
|
||
const override = schemaOverride(target, database);
|
||
const hasPattern = (value: string) => /[*?]/.test(value);
|
||
const protectedRules = database === null && (listDatabases ? intro?.databases : intro?.schemas)?.some(hasPattern);
|
||
const names =
|
||
databases?.status === "ok"
|
||
? {
|
||
available: databases.value.names,
|
||
visible: shownDatabases(sourceId, databases.value),
|
||
current: databases.value.current,
|
||
restore: () => shownNames(databases.value.names, false, intro?.databases, databases.value.current),
|
||
}
|
||
: schemas?.status === "ok"
|
||
? {
|
||
available: schemas.value,
|
||
visible: shownSchemas(target, schemas.value, database),
|
||
defaults: database === null ? undefined : defaultSchemas(target, schemas.value),
|
||
restore: () =>
|
||
database === null
|
||
? shownNames(schemas.value, false, intro?.schemas)
|
||
: override
|
||
? exactNames(schemas.value, override.names ?? [])
|
||
: defaultSchemas(target, schemas.value),
|
||
}
|
||
: undefined;
|
||
const initial =
|
||
database !== null
|
||
? override
|
||
? { all: !!override.all, names: override.names ?? [] }
|
||
: null
|
||
: listDatabases
|
||
? { all: intro?.allDatabases !== false, names: intro?.databases ?? [] }
|
||
: { all: intro?.allSchemas !== false, names: intro?.schemas ?? [] };
|
||
const metadata = databases ?? schemas;
|
||
return (
|
||
<IntrospectionPicker
|
||
title={formatMessage(title, { name })}
|
||
kind={kind}
|
||
names={names}
|
||
initial={initial}
|
||
tabIndex={lead ? 0 : -1}
|
||
protectedRules={!!protectedRules}
|
||
editableName={(name) => database !== null || (!protectedRules && !hasPattern(name))}
|
||
loadError={metadata?.status === "error" ? metadata.message : undefined}
|
||
onLoad={() => {
|
||
if (metadata?.status !== "loading") void load(n);
|
||
}}
|
||
onApply={async (selection) => {
|
||
const available = names?.available ?? [];
|
||
if (database !== null) {
|
||
await saveSourceVisibility(sourceId, available, { kind: "databaseSchemas", database, selection });
|
||
} else if (selection) {
|
||
await saveSourceVisibility(sourceId, available, {
|
||
kind: listDatabases ? "databases" : "schemas",
|
||
selection,
|
||
});
|
||
}
|
||
}}
|
||
/>
|
||
);
|
||
};
|
||
|
||
const expandable = (n: Node) =>
|
||
n.kind === "source" ||
|
||
n.kind === "sourceFolder" ||
|
||
n.kind === "database" ||
|
||
n.kind === "schema" ||
|
||
n.kind === "folder" ||
|
||
n.kind === "table" ||
|
||
n.kind === "group";
|
||
|
||
// Expand All opens the nodes already loaded: it connects to nothing and runs no query.
|
||
useEffect(() => {
|
||
databaseTree.expandAll = () => {
|
||
const next = new Set(useDatabase.getState().treeExpanded);
|
||
const walk = (nodes: readonly Node[]) => {
|
||
for (const n of nodes) {
|
||
const kids = expandable(n) ? children(n) : undefined;
|
||
if (!kids) continue;
|
||
next.add(n.key);
|
||
walk(kids);
|
||
}
|
||
};
|
||
walk(roots);
|
||
useDatabase.setState({ treeExpanded: next });
|
||
};
|
||
return () => {
|
||
databaseTree.expandAll = null;
|
||
};
|
||
});
|
||
|
||
/** The shown nodes with keys in `keys`, in tree order. */
|
||
const shownNodes = (keys: ReadonlySet<string>): Node[] => {
|
||
const out: Node[] = [];
|
||
const walk = (nodes: readonly Node[]) => {
|
||
for (const n of nodes) {
|
||
if (keys.has(n.key)) out.push(n);
|
||
if (st.treeExpanded.has(n.key)) walk(children(n) ?? []);
|
||
}
|
||
};
|
||
walk(roots);
|
||
return out;
|
||
};
|
||
|
||
const label = (n: Node): string => {
|
||
switch (n.kind) {
|
||
case "workspace":
|
||
return t("Query Workspace");
|
||
case "source":
|
||
return n.source.pluginOwner ? `${n.source.name} (${n.source.pluginOwner})` : (n.source.name ?? "");
|
||
case "sourceFolder":
|
||
return n.folder.name;
|
||
case "database":
|
||
return n.name;
|
||
case "schema":
|
||
return n.schema;
|
||
case "folder":
|
||
return t(FOLDER_LABELS[n.folder]);
|
||
case "routine":
|
||
return n.routine.name;
|
||
case "package":
|
||
return n.package.name;
|
||
case "sequence":
|
||
return n.sequence.name;
|
||
case "object":
|
||
return n.object.name;
|
||
case "trigger":
|
||
return n.trigger.name;
|
||
case "table":
|
||
return n.table.name;
|
||
case "group":
|
||
return t(GROUP_LABELS[n.group]);
|
||
case "column":
|
||
return n.column.name;
|
||
// Unnamed (SQLite) keys are numbered like IDEA's `key #1` / `foreign-key #1`.
|
||
case "key":
|
||
return "key #1";
|
||
case "foreignKey":
|
||
return `foreign-key #${Number(n.key.slice(n.key.lastIndexOf("/") + 1)) + 1}`;
|
||
case "index":
|
||
return n.index.name;
|
||
case "message":
|
||
return n.text;
|
||
}
|
||
};
|
||
|
||
/** Grey text after the label: counts, column types, key columns. */
|
||
const detail = (n: Node): string | undefined => {
|
||
switch (n.kind) {
|
||
case "source": {
|
||
if (n.source.driver !== "sqlite") return undefined;
|
||
const id = n.source.id ?? "";
|
||
const s = st.schemas[id];
|
||
return s?.status === "ok" ? String(shownSchemas(id, s.value, null).length) : undefined;
|
||
}
|
||
case "sourceFolder":
|
||
return String(n.folder.sources.length);
|
||
case "folder":
|
||
return String(folderSize(n.id, n.schema, n.folder, n.catalog));
|
||
case "routine":
|
||
return `(${n.routine.arguments})${n.routine.returns ? `: ${n.routine.returns}` : ""}`;
|
||
case "sequence":
|
||
return n.sequence.dataType;
|
||
case "object":
|
||
return n.object.detail || undefined;
|
||
case "trigger":
|
||
return `${n.trigger.timing} ${n.trigger.events}`.trim();
|
||
case "group": {
|
||
const d = detailsOf(n.id, n.schema, n.table, n.catalog);
|
||
return d ? String(groupSize(d, n.group)) : undefined;
|
||
}
|
||
case "column":
|
||
return n.column.dataType;
|
||
case "key":
|
||
return `(${n.columns.join(", ")})`;
|
||
case "foreignKey":
|
||
return `(${n.fk.columns.join(", ")}) → ${n.fk.refTable} (${n.fk.refColumns.join(", ")})`;
|
||
case "index":
|
||
return `${n.index.unique ? "unique " : ""}(${n.index.columns.join(", ")})`;
|
||
case "table": {
|
||
if (!st.showTableComments) return undefined;
|
||
const comment = n.table.comment?.replace(/\s+/g, " ").trim();
|
||
return comment || undefined;
|
||
}
|
||
default:
|
||
return undefined;
|
||
}
|
||
};
|
||
|
||
const icon = (n: Node): string | undefined => {
|
||
switch (n.kind) {
|
||
case "workspace":
|
||
return "db-console";
|
||
case "source":
|
||
return sourceIcon(n.source);
|
||
case "sourceFolder":
|
||
return "db-folder";
|
||
case "database":
|
||
return "db-database";
|
||
case "schema":
|
||
return "db-schema";
|
||
case "folder":
|
||
case "group":
|
||
return "db-folder";
|
||
case "table":
|
||
return n.table.kind === "view" ? "db-view" : n.table.kind === "materializedView" ? "db-matview" : "db-table";
|
||
case "routine":
|
||
return "db-routine";
|
||
case "package":
|
||
return "db-routine";
|
||
case "sequence":
|
||
return "db-sequence";
|
||
case "object":
|
||
return n.object.kind === "stage" ? "db-folder" : n.object.kind === "stream" ? "db-table" : "db-routine";
|
||
case "trigger":
|
||
return "db-trigger";
|
||
case "column":
|
||
return n.column.primaryKey ? "db-column-key" : n.foreignKey ? "db-column-fk" : "db-column";
|
||
case "key":
|
||
return "db-key";
|
||
case "foreignKey":
|
||
return "db-foreign-key";
|
||
case "index":
|
||
return "db-index";
|
||
case "message":
|
||
return n.error ? "error" : undefined;
|
||
}
|
||
};
|
||
|
||
const empty = st.loaded && st.foldersLoaded && !st.sources.length && !st.folders.length;
|
||
return (
|
||
<div className={styles.dbView}>
|
||
<DatabaseToolbar />
|
||
<div className={styles.treeHost} ref={treeHost} data-empty={empty ? "" : undefined}>
|
||
<Tree<Node>
|
||
aria-label="Data sources"
|
||
focusContext={DB_VIEW_FOCUS}
|
||
roots={roots}
|
||
handleRef={tree}
|
||
expanded={st.treeExpanded}
|
||
onExpandedChange={(treeExpanded) => useDatabase.setState({ treeExpanded })}
|
||
getKey={(n) => n.key}
|
||
getLabel={label}
|
||
getChildren={children}
|
||
isExpandable={expandable}
|
||
loadChildren={load}
|
||
getIcon={(n) => icon(n)}
|
||
getDetail={detail}
|
||
getTooltip={(n) =>
|
||
n.kind === "source"
|
||
? n.source.comment || undefined
|
||
: n.kind === "table" && st.showTableComments
|
||
? n.table.comment?.trim() || undefined
|
||
: undefined
|
||
}
|
||
rowClassName={(n) =>
|
||
n.kind === "sourceFolder" && dropFolder === n.folder.id ? styles.sourceFolderDrop : undefined
|
||
}
|
||
getColor={(n) => (n.kind === "message" && n.error ? "var(--danger)" : undefined)}
|
||
rowTint={(n) => {
|
||
// IDEA tints every row of a coloured data source across its full width and height.
|
||
const target = nodeTarget(n);
|
||
const color = target ? sourceOf(target)?.color : null;
|
||
return color ? `var(--db-color-${color})` : undefined;
|
||
}}
|
||
speedSearchField
|
||
horizontalScroll
|
||
getDragData={(nodes) => {
|
||
const ids = nodes.flatMap((node) => (node.kind === "source" ? [node.source.id ?? ""] : [])).filter(Boolean);
|
||
return ids.length ? { type: SOURCE_DRAG, payload: JSON.stringify(ids) } : null;
|
||
}}
|
||
renderNode={(n: Node, state) => {
|
||
const i = icon(n);
|
||
const d = detail(n);
|
||
const counted =
|
||
n.kind === "source" || n.kind === "sourceFolder" || n.kind === "folder" || n.kind === "group";
|
||
const labelClass =
|
||
n.kind === "message" && n.error
|
||
? styles.treeError
|
||
: n.kind === "key" || n.kind === "foreignKey"
|
||
? styles.keyLabel
|
||
: styles.nodeLabel;
|
||
const live = n.kind === "source" && [...st.connected].some((t) => splitTarget(t).id === n.source.id);
|
||
const title =
|
||
n.kind === "source"
|
||
? n.source.comment || undefined
|
||
: n.kind === "table" && st.showTableComments
|
||
? n.table.comment?.trim() || undefined
|
||
: undefined;
|
||
return (
|
||
<span className={styles.nodeRow} title={title}>
|
||
{i && (
|
||
<span className={styles.nodeIcon}>
|
||
<Icon name={i} size={16} />
|
||
{/* IDEA: a green dot on the data source icon while connected. */}
|
||
{live && <span className={styles.connectedDot} title={tx("Connected")} />}
|
||
</span>
|
||
)}
|
||
<HighlightedText className={labelClass} text={label(n)} indices={state.matches} />
|
||
{n.kind === "source" && n.source.global && (
|
||
<span className={styles.treeDetail} title={tx("Available in all projects")}>
|
||
{tx("global")}
|
||
</span>
|
||
)}
|
||
{picker(n, state.lead)}
|
||
{d && (
|
||
<span
|
||
className={
|
||
n.kind === "source"
|
||
? styles.treeBadge
|
||
: counted
|
||
? styles.treeCount
|
||
: n.kind === "column"
|
||
? styles.treeType
|
||
: styles.treeDetail
|
||
}
|
||
>
|
||
{d}
|
||
</span>
|
||
)}
|
||
</span>
|
||
);
|
||
}}
|
||
onSelectionChange={(selected, lead) =>
|
||
useDatabase.setState({
|
||
selectedSource: lead ? nodeTarget(lead) : null,
|
||
selectedNode: lead,
|
||
// Not just the lead: a ⌘-click that deselects a row still makes it the lead.
|
||
selectedNodes: shownNodes(selected),
|
||
})
|
||
}
|
||
onActivate={(n) => {
|
||
if (n.kind === "workspace") void executeAction("db.queryWorkspace");
|
||
else if (n.kind === "table") openTableData(n.id, n.schema, n.table.name, n.catalog);
|
||
else if (n.kind === "source") void openConsole(n.source.id ?? "");
|
||
else if (n.kind === "database" && n.catalog === undefined) void openConsole(n.id);
|
||
else {
|
||
const o = schemaObjectOf(n);
|
||
if (o) void openObjectDdl(o.id, o.schema, o.kind, o.name);
|
||
}
|
||
}}
|
||
activateExpandable={(n) => n.kind === "table"}
|
||
onContextMenu={(n, selection, e) => {
|
||
const items = nodeMenu(n, shownNodes(selection));
|
||
if (items.length) showContextMenu(e, items);
|
||
}}
|
||
speedSearch
|
||
/>
|
||
{empty && (
|
||
<EmptyState title="No data sources">
|
||
<Button variant="ghost" onClick={() => void executeAction("db.newDataSource")}>
|
||
<T>New Data Source…</T>
|
||
</Button>
|
||
<Button variant="ghost" onClick={() => void executeAction("db.newSourceFolder")}>
|
||
<T>New Folder…</T>
|
||
</Button>
|
||
</EmptyState>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* The toolbar row of IDEA's Database tool window, always shown under the
|
||
* title: New ▸, Properties | Refresh, Deactivate | Jump to Query Console,
|
||
* Edit Data, DDL.
|
||
*/
|
||
function DatabaseToolbar() {
|
||
const node = useDatabase((s) => s.selectedNode);
|
||
const selectedNodes = useDatabase((s) => s.selectedNodes);
|
||
const connected = useDatabase((s) => s.connected);
|
||
const sources = useDatabase((s) => s.sources);
|
||
const plus = useRef<HTMLButtonElement>(null);
|
||
const newOpen = useDatabase((s) => s.newMenuOpen);
|
||
const setNewOpen = (v: boolean) => useDatabase.setState({ newMenuOpen: v });
|
||
const table = node?.kind === "table" || node?.kind === "column" || node?.kind === "group";
|
||
const target = node ? nodeTarget(node) : sources.length === 1 ? (sources[0]!.id ?? null) : null;
|
||
const selectedSources = selectedNodes.filter((selected) => selected.kind === "source");
|
||
const multiSource = selectedSources.length > 1;
|
||
const active = multiSource
|
||
? selectedSources.some((selected) =>
|
||
[...connected].some((connectedTarget) => splitTarget(connectedTarget).id === selected.source.id),
|
||
)
|
||
: !!target && [...connected].some((t) => splitTarget(t).id === splitTarget(target).id);
|
||
const button = { size: "small", iconSize: 16 } as const;
|
||
return (
|
||
<Toolbar className={styles.dbToolbar} aria-label="Database actions">
|
||
<IconButton
|
||
ref={plus}
|
||
{...button}
|
||
icon="db-add"
|
||
title="New"
|
||
shortcut={shortcutLabel("db.new")}
|
||
aria-haspopup="menu"
|
||
aria-expanded={newOpen}
|
||
onClick={() => setNewOpen(!newOpen)}
|
||
/>
|
||
<Menu
|
||
open={newOpen}
|
||
anchor={plus}
|
||
items={newMenu()}
|
||
placement="bottom-start"
|
||
onClose={() => setNewOpen(false)}
|
||
aria-label="New"
|
||
/>
|
||
<IconButton
|
||
{...button}
|
||
icon="db-properties"
|
||
action="db.properties"
|
||
disabled={!sources.length || multiSource || node?.kind === "sourceFolder"}
|
||
/>
|
||
<span className={styles.dbToolbarSep} />
|
||
<IconButton {...button} icon="refresh" action="db.refresh" disabled={!sources.length} />
|
||
<IconButton
|
||
{...button}
|
||
icon="db-disconnect"
|
||
action="db.disconnect"
|
||
disabled={multiSource ? !active : node ? !active : !connected.size}
|
||
/>
|
||
<span className={styles.dbToolbarSep} />
|
||
<IconButton {...button} icon="db-console" action="db.jumpToConsole" disabled={!target} />
|
||
<IconButton {...button} icon="db-table" action="db.editData" disabled={!table} />
|
||
{/* IDEA labels this one with text. */}
|
||
<button
|
||
type="button"
|
||
className={styles.textTool}
|
||
aria-label={tx("Go to DDL")}
|
||
disabled={!table}
|
||
onClick={() => void executeAction("db.goToDdl")}
|
||
{...tooltipAttrs("Go to DDL", shortcutLabel("db.goToDdl"))}
|
||
>
|
||
<T>DDL</T>
|
||
</button>
|
||
</Toolbar>
|
||
);
|
||
}
|
||
|
||
/** Header controls (shown on hover, like IDEA's): Select Opened File, Expand All, Collapse All. */
|
||
export function DatabaseHeaderActions() {
|
||
return (
|
||
<>
|
||
<IconButton icon="locate" action="db.selectOpened" size="small" iconSize={16} />
|
||
<IconButton icon="expand-all" action="db.expandAll" size="small" iconSize={16} />
|
||
<IconButton icon="collapse-all" action="db.collapseAll" size="small" iconSize={16} />
|
||
</>
|
||
);
|
||
}
|