feat(database): choose tree visibility from row counts (#4824)

The count on a Database tree row opens a searchable chooser for what that row shows, without opening Data Source Properties: PostgreSQL source rows choose databases and database rows choose schemas (each database inherits the source rules until overridden, stored as schemasByDatabase); ClickHouse keeps a flat database list. A visibility-only save updates the rules against the latest saved file and keeps the connection and loaded metadata, while wildcard rules and names the server did not return are preserved.

Closes #4781

Co-authored-by: principalwater <[email protected]>
Цей коміт міститься в:
Vladislav Kuzmin authored and GitHub committed 2026-11-22 00:38:27 +08:00
1 джерело aaab9a5dc6
коміт 65b0cc45f0
15 files changed
+1137 -38

No files matched your search

+46
Переглянути файл
@@ -229,6 +229,52 @@
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.introspectionTrigger {
display: inline-flex;
flex: none;
}
.introspectionCount {
display: inline-flex;
align-items: center;
padding: 0 var(--space-1);
background: transparent;
color: var(--fg-secondary);
border: 1px solid var(--border);
border-radius: var(--radius-small);
font: inherit;
font-size: var(--fs-small);
line-height: 16px;
}
.introspectionCount:hover,
.introspectionCount:focus-visible,
.introspectionCount[aria-expanded="true"] {
color: var(--fg-strong);
border-color: var(--accent);
}
.introspectionPopup {
display: flex;
flex-direction: column;
width: min(276px, calc(100vw - 24px));
padding: var(--space-2);
gap: var(--space-2);
}
.introspectionModes,
.introspectionNames {
display: grid;
align-content: start;
gap: var(--space-1);
}
.introspectionNames {
max-height: min(220px, 40vh);
overflow: auto;
padding: var(--space-1);
border-block: 1px solid var(--border);
}
.introspectionActions {
display: flex;
justify-content: flex-end;
gap: var(--space-2);
}
.textTool {
flex: none;
height: 20px;
+101 -17
Переглянути файл
@@ -24,6 +24,7 @@ import {
T,
} from "@/ui";
import { databaseKey, passesObjectFilter, shownNames, sourceIcon, splitTarget, targetOf } from "./model";
import { IntrospectionPicker } from "./IntrospectionPicker";
import {
nodeTarget,
isOtherFolder,
@@ -46,6 +47,7 @@ import {
loadTables,
openConsole,
openObjectDdl,
saveSourceVisibility,
tablesKey,
useDatabase,
type Loaded,
@@ -53,7 +55,7 @@ import {
import { DB_VIEW_FOCUS, databaseTree, openTableData } from "./treeActions";
import { newMenu, nodeMenu } from "./treeMenu";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
import { formatMessage, tx } from "@/platform/i18n";
import { databaseRequest } from "./requests";
const GROUP_LABELS: Record<Group, string> = {
@@ -187,19 +189,31 @@ export function DatabaseView() {
};
const sourceOf = (target: string) => st.sources.find((s) => s.id === splitTarget(target).id);
/** The Schemas tab's choice. */
const shownSchemas = (target: string, names: string[]) => {
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) =>
const schemasOf = (key: string, id: string, database: string | null) =>
status(key, st.schemas[id], (v) =>
shownSchemas(id, v).map((schema) => ({ kind: "schema", key: `${id}/${schema}`, id, schema }) as Node),
shownSchemas(id, v, database).map((schema) => ({ kind: "schema", key: `${id}/${schema}`, id, schema }) as Node),
);
const children = (n: Node): readonly Node[] | undefined => {
@@ -216,10 +230,10 @@ export function DatabaseView() {
current: name === v.current,
})),
);
return schemasOf(n.key, id);
return schemasOf(n.key, id, null);
}
case "database":
return schemasOf(n.key, n.id);
return schemasOf(n.key, n.id, n.name);
case "schema":
return status(n.key, st.tables[tablesKey(n.id, n.schema)], () =>
folders
@@ -341,6 +355,82 @@ export function DatabaseView() {
else if (n.kind === "table") await loadDetails(n.id, n.schema, n.table.name);
};
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 && listsDatabases(source);
const databases = listDatabases ? st.databases[sourceId] : undefined;
const schemas = listDatabases ? undefined : st.schemas[target];
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 === "database" ||
@@ -411,17 +501,10 @@ export function DatabaseView() {
const detail = (n: Node): string | undefined => {
switch (n.kind) {
case "source": {
if (n.source.driver !== "sqlite") return undefined;
const id = n.source.id ?? "";
if (listsDatabases(n.source)) {
const d = st.databases[id];
return d?.status === "ok" ? String(shownDatabases(id, d.value).length) : undefined;
}
const s = st.schemas[id];
return s?.status === "ok" ? String(shownSchemas(id, s.value).length) : undefined;
}
case "database": {
const s = st.schemas[n.id];
return s?.status === "ok" ? String(shownSchemas(n.id, s.value).length) : undefined;
return s?.status === "ok" ? String(shownSchemas(id, s.value, null).length) : undefined;
}
case "folder":
return String(folderSize(n.id, n.schema, n.folder));
@@ -528,7 +611,7 @@ export function DatabaseView() {
renderNode={(n: Node, state) => {
const i = icon(n);
const d = detail(n);
const counted = n.kind === "source" || n.kind === "database" || n.kind === "folder" || n.kind === "group";
const counted = n.kind === "source" || n.kind === "folder" || n.kind === "group";
const labelClass =
n.kind === "message" && n.error
? styles.treeError
@@ -554,6 +637,7 @@ export function DatabaseView() {
{tx("global")}
</span>
)}
{picker(n, state.lead)}
{d && (
<span
className={
+234
Переглянути файл
@@ -0,0 +1,234 @@
import { useId, useRef, useState, type RefObject } from "react";
import { tx } from "@/platform/i18n";
import { isImeKey } from "@/platform/ime";
import { Button, Checkbox, Icon, Input, Popup, T } from "@/ui";
import styles from "./Database.module.css";
interface Selection {
all: boolean;
names: string[];
}
interface Names {
available: string[];
visible: string[];
defaults?: string[];
current?: string | null;
restore: () => string[];
}
interface Props {
title: string;
kind: "databases" | "schemas";
names: Names | undefined;
initial: Selection | null;
tabIndex: number;
protectedRules: boolean;
editableName: (name: string) => boolean;
loadError?: string;
onLoad: () => void;
onApply: (selection: Selection | null) => Promise<void>;
}
/** A database row can inherit its source's schema rules; source rows edit those rules directly. */
export function IntrospectionPicker(props: Props) {
const { title, names, onLoad, loadError, tabIndex } = props;
const anchor = useRef<HTMLButtonElement>(null);
const [open, setOpen] = useState(false);
const used = names?.visible.length ?? 0;
const total = names?.available.length ?? 0;
const close = () => setOpen(false);
return (
<span
className={styles.introspectionTrigger}
onMouseDown={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
if (e.key !== "Escape" && e.key !== "Tab") e.stopPropagation();
}}
>
<button
ref={anchor}
type="button"
className={styles.introspectionCount}
aria-label={title}
aria-haspopup="dialog"
aria-expanded={open}
tabIndex={tabIndex}
title={title}
onClick={() => {
if (open) return;
setOpen(true);
if (!names && !loadError) onLoad();
}}
>
{names ? tx`${used} of ${total}` : <Icon name="filter" size={12} />}
</button>
{open && <PickerPopup {...props} anchor={anchor} onClose={close} />}
</span>
);
}
function PickerPopup({
title,
kind,
names,
initial,
loadError,
onLoad,
onApply,
anchor,
onClose,
protectedRules,
editableName,
}: Props & { anchor: RefObject<HTMLButtonElement | null>; onClose: () => void }) {
const [query, setQuery] = useState("");
const [draft, setDraft] = useState<Selection | null>();
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string>();
const patternHint = useId();
const selection = draft === undefined ? initial : draft;
const marked = new Set(
draft === undefined
? names?.visible
: draft === null
? names?.defaults
: draft.all
? names?.available
: draft.names,
);
if (names?.current) marked.add(names.current);
const filter = query.trim().toLocaleLowerCase();
const matches = names?.available.filter((name) => name.toLocaleLowerCase().includes(filter));
const apply = async () => {
if (saving) return;
if (draft === undefined) {
onClose();
return;
}
try {
setSaving(true);
setSaveError(undefined);
await onApply(draft);
onClose();
} catch (e) {
setSaveError(e instanceof Error ? e.message : String(e));
setSaving(false);
}
};
return (
<Popup
open
anchor={anchor}
placement="bottom-end"
aria-label={title}
aria-describedby={names && protectedRules ? patternHint : undefined}
trapFocus
closeOnDeactivate={false}
onClose={(reason) => {
if (saving) return;
if (reason === "outside") void apply();
else onClose();
}}
>
<div
className={styles.introspectionPopup}
onKeyDown={(e) => {
if (e.key === "Enter" && e.target instanceof HTMLInputElement && !isImeKey(e.nativeEvent)) {
e.preventDefault();
void apply();
}
}}
>
{names ? (
<>
<Input
autoFocus
aria-label="Filter names"
placeholder="Filter names"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<div className={styles.introspectionModes}>
{names.defaults && (
<Checkbox
label="Use source settings"
checked={selection === null}
disabled={saving}
onChange={(inherit) => setDraft(inherit ? null : { all: false, names: [...marked] })}
/>
)}
<Checkbox
label={kind === "databases" ? tx("All databases") : tx("All schemas")}
checked={selection?.all === true}
disabled={saving}
onChange={(all) => setDraft({ all, names: all ? [] : names.restore() })}
/>
</div>
<div className={styles.introspectionNames}>
{matches?.length ? (
matches.map((name) => (
<Checkbox
key={name}
label={
<>
{name}
{name === names.current && (
<span className={styles.treeDetail}>
{" "}
<T>Current database</T>
</span>
)}
</>
}
checked={marked.has(name)}
disabled={saving || name === names.current || !editableName(name)}
onChange={(checked) => {
if (checked) marked.add(name);
else marked.delete(name);
setDraft({ all: false, names: names.available.filter((item) => marked.has(item)) });
}}
/>
))
) : (
<span className={styles.treeDetail}>
<T>No matching names</T>
</span>
)}
</div>
{protectedRules && (
<span id={patternHint} className={styles.treeDetail}>
<T>Edit name patterns in Data Source Properties.</T>
</span>
)}
</>
) : loadError ? (
<div className={styles.introspectionModes}>
<span role="alert">{loadError}</span>
<Button onClick={onLoad}>
<T>Retry</T>
</Button>
</div>
) : !saveError ? (
<span role="status">
<T>Loading…</T>
</span>
) : null}
{saveError && <span role="alert">{saveError}</span>}
{names && (
<span className={styles.treeDetail}>
<T>Enter or click outside to apply</T>
</span>
)}
<div className={styles.introspectionActions}>
<Button disabled={saving} onClick={onClose}>
<T>Cancel</T>
</Button>
<Button variant="primary" disabled={saving || (!names && draft === undefined)} onClick={() => void apply()}>
<T>Apply</T>
</Button>
</div>
</div>
</Popup>
);
}
+42
Переглянути файл
@@ -642,6 +642,48 @@ describe("completion requests", () => {
expect(backend.completion).toHaveBeenCalledTimes(2);
});
it("drops only the edited JDBC completion model when its schema rules change", async () => {
const jdbc: DataSource = { ...pg, driver: "jdbc", introspection: { allSchemas: false, schemas: ["APP_*"] } };
savedSources = [jdbc, other];
await loadSources();
await loadSchemas("pg");
await loadCompletion("pg");
await loadCompletion("pg2");
const schemas = useDatabase.getState().schemas;
await saveSource({ ...jdbc, introspection: { allSchemas: false, schemas: ["REPORTS"] } }, undefined);
const state = useDatabase.getState();
expect(state.completion.pg).toBeUndefined();
expect(state.completion.pg2).toEqual(completion);
expect(state.schemas).toBe(schemas);
expect(state.connected.has("pg")).toBe(true);
expect(backend.schemas).toHaveBeenCalledOnce();
expect(backend.completion).toHaveBeenCalledTimes(2);
expect(await loadCompletion("pg")).toEqual(completion);
expect(backend.completion).toHaveBeenCalledTimes(3);
});
it("ignores an old JDBC completion response after its schema rules change", async () => {
const jdbc: DataSource = { ...pg, driver: "jdbc" };
savedSources = [jdbc, other];
await loadSources();
const old = deferred();
const fresh = deferred();
backend.completion.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise);
const previous = loadCompletion("pg");
await saveSource({ ...jdbc, introspection: { allSchemas: false, schemas: ["APP"] } }, undefined);
const next = loadCompletion("pg");
expect(next).not.toBe(previous);
old.resolve(ok({ ...completion, defaultSchema: "old" }));
expect(await previous).toBeNull();
expect(useDatabase.getState().completion.pg).toBeUndefined();
expect(loadCompletion("pg")).toBe(next);
fresh.resolve(ok(completion));
expect(await next).toEqual(completion);
});
it("lets completion recover after failure", async () => {
backend.completion.mockRejectedValueOnce(new Error("not available"));
expect(await loadCompletion("pg")).toBeNull();
+67 -6
Переглянути файл
@@ -17,6 +17,7 @@ import {
type DbCompletion,
type DbDatabases,
type DbDriver,
type DbIntrospection_Deserialize,
type ExecutionEvent,
type DbObjectKind,
type DbPlanNode,
@@ -25,6 +26,7 @@ import {
type DbTableDetails,
type DbTableInfo,
type DbTableKind,
type DbVisibilityChange,
type RequestId,
type SqlStatement,
} from "@/platform/ipc";
@@ -346,6 +348,30 @@ function sourceMutation(id: string): () => boolean {
return () => project() && sourceMutations.get(id) === intent;
}
/** The cached names come from the server before the visibility rules are applied. */
function sourceMetadataKey(source: DataSource | undefined): string | undefined {
if (!source) return undefined;
const { introspection, ...connection } = source;
const metadata: DbIntrospection_Deserialize = {
...introspection,
showSystem: !!introspection?.showSystem,
showTemplates: !!introspection?.showTemplates,
};
delete metadata.allDatabases;
delete metadata.databases;
delete metadata.allSchemas;
delete metadata.schemas;
delete metadata.schemasByDatabase;
delete metadata.objectFilter;
return JSON.stringify([connection, metadata]);
}
function jdbcSchemaRuleKey(source: DataSource): string | undefined {
const rules = source.introspection;
if (rules?.allSchemas !== false) return undefined;
return JSON.stringify([...new Set(rules.schemas?.map((pattern) => pattern.trim()).filter(Boolean))].sort());
}
export async function loadSources(): Promise<void> {
// Closing the project resets `loaded` while its SQL consoles are still mounted.
if (!useProject.getState().project) return;
@@ -356,8 +382,20 @@ export async function loadSources(): Promise<void> {
try {
const [sources, connected] = await Promise.all([call(commands.dbSources()), call(commands.dbConnected())]);
if (request !== sourcesRequest || !current()) return;
const staleCompletionSources = new Set<string>();
for (const old of useDatabase.getState().sources) {
if (JSON.stringify(old) !== JSON.stringify(sources.find((s) => s.id === old.id))) forget(old.id ?? "");
const next = sources.find((s) => s.id === old.id);
const id = old.id ?? "";
if (sourceMetadataKey(old) !== sourceMetadataKey(next)) forget(id);
else if (old.driver === "jdbc" && next && jdbcSchemaRuleKey(old) !== jdbcSchemaRuleKey(next)) {
staleCompletionSources.add(id);
}
}
if (staleCompletionSources.size) {
// JDBC completion uses the source's schema rules. Raw names and live sessions do not.
for (const target of completionLoads.keys()) {
if (staleCompletionSources.has(splitTarget(target).id)) completionLoads.delete(target);
}
}
useDatabase.setState((s) => {
const server = new Set(connected);
@@ -370,7 +408,12 @@ export async function loadSources(): Promise<void> {
sourceIntents.get(sourceId) !== sourceConnectionIntents.get(sourceId);
return changed ? s.connected.has(target) : server.has(target);
});
return { sources, connected: new Set(live), loaded: true };
const completion = staleCompletionSources.size
? Object.fromEntries(
Object.entries(s.completion).filter(([target]) => !staleCompletionSources.has(splitTarget(target).id)),
)
: s.completion;
return { sources, connected: new Set(live), completion, loaded: true };
});
} catch (e) {
if (request !== sourcesRequest || !current()) return;
@@ -410,11 +453,15 @@ export async function saveSource(
): Promise<void> {
const id = source.id ?? "";
const st = useDatabase.getState();
const preserve =
password === undefined &&
sshSecret === undefined &&
sourceMetadataKey(st.sources.find((s) => s.id === id)) === sourceMetadataKey(source);
const loaded = id in st.databases || Object.keys(st.schemas).some((t) => splitTarget(t).id === id);
// Taken before anything is forgotten: what the tree had expanded under this source.
const levels = loadedLevels(id);
const levels = !preserve && loaded ? loadedLevels(id) : undefined;
const connection = connectionIntents.get(id);
forget(id);
if (!preserve) forget(id);
const current = sourceMutation(id);
const sources = useDatabase.getState().sources;
const next = sources.some((s) => s.id === source.id)
@@ -431,7 +478,21 @@ export async function saveSource(
// expanded nodes don't stay on Loading.
await loadSources();
if (!current() || !sourceById(id)) return;
if (loaded && connectionIntents.get(id) === connection) await refresh(id, levels);
if (levels && connectionIntents.get(id) === connection) await refresh(id, levels);
}
export async function saveSourceVisibility(id: string, available: string[], change: DbVisibilityChange): Promise<void> {
const current = projectRequest();
try {
await call(commands.dbSaveSourceVisibility(id, available, change));
} catch (e) {
// This command is deliberately separate: older hosts reject it before writing or disconnecting.
if (message(e).includes("command db_save_source_visibility is not available remotely")) {
throw new Error(tx("Update the remote OpenIDEA server to edit visibility from the tree."), { cause: e });
}
throw e;
}
if (current()) await loadSources();
}
/** Copy/Paste › Duplicate: a copy of data source `id` named `<name> [2]` (its password is not copied). */
@@ -909,7 +970,7 @@ export function loadCompletion(id: string): Promise<DbCompletion | null> {
const current = databaseRequest(id);
const promise = call(commands.dbCompletion(id))
.then((model) => {
if (!current()) return null;
if (!current() || completionLoads.get(id)?.promise !== promise) return null;
useDatabase.setState((s) => ({ completion: { ...s.completion, [id]: model } }));
return model;
})