дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
The grid's Copy as submenu gets SQL INSERT, SQL UPDATE and SQL DELETE for the whole selected rows, and the data extractors get SQL Updates, SQL Deletes and Where Clause beside SQL Inserts. A row is matched by its primary key, which the exported columns now carry; without one, by every column, which the copied text says first. A NULL value is matched with IS NULL. The SQL literal rule lives in one helper for One-Row and the SQL formats. Fixes #6143
935 рядки
36 KiB
TypeScript
935 рядки
36 KiB
TypeScript
/**
|
|
* Database Console service view (IDEA's): an Output tab logging every
|
|
* executed statement with its outcome, and a `Result N` tab per result set —
|
|
* a toolbar (re-run, export / copy as CSV, JSON, SQL…), the grid and a floating row count.
|
|
*/
|
|
import { canModifyTable } from "./objects";
|
|
import { copySelectionOnKeyDown } from "@/ui/selectableText";
|
|
import {
|
|
useCallback,
|
|
useEffect,
|
|
useLayoutEffect,
|
|
useMemo,
|
|
useRef,
|
|
useState,
|
|
useSyncExternalStore,
|
|
type MouseEvent,
|
|
} from "react";
|
|
import clsx from "clsx";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import { basename } from "@/platform/project";
|
|
import { call, commands, type DbPlanNode, type DbQueryResult } from "@/platform/ipc";
|
|
import { shortcutLabel } from "@/platform/keymap";
|
|
import { setContext } from "@/platform/context";
|
|
import { EmptyState, Icon, IconButton, Select, Spinner, Tabs, Tree, showContextMenu, T, Toolbar } from "@/ui";
|
|
import { notifications } from "@/workbench/contributions";
|
|
import { ToolWindowContentTabs } from "@/workbench/toolwindows/ToolWindows";
|
|
import { ChartView } from "./ChartView";
|
|
import { ColumnsPopup } from "./ColumnsPopup";
|
|
import { cellOf, cutLength, hasCutCells, loadCells, loadPage, rowsOf, useCutCells } from "./cutCells";
|
|
import { DataView, ExtractorSelect, PanelToggle, copyFormatOf, exportMenu, type DataPanel } from "./DataView";
|
|
import type { ExportData, ExportFormat } from "./export";
|
|
import { buildRowEdits, emptyEdits, hasEdits, splitTarget, type Cell, type PendingEdits } from "./model";
|
|
import {
|
|
editStatements,
|
|
pkResultColumns,
|
|
resultColumnSources,
|
|
resultEditability,
|
|
resolveTarget,
|
|
type EditBlockReason,
|
|
} from "./resultEditing";
|
|
import { formatElapsed, pageWindow } from "./resultView";
|
|
import { resultTabMenu } from "./resultTabActions";
|
|
import { analyze } from "./sql/analyze";
|
|
import { nameMatcher } from "./sql/dialect";
|
|
import {
|
|
OUTPUT_TAB,
|
|
clearOutput,
|
|
closeResult,
|
|
countResult,
|
|
countable,
|
|
detailsKey,
|
|
loadDetails,
|
|
loadResultPage,
|
|
log,
|
|
outcomeSummary,
|
|
pageable,
|
|
pinResult,
|
|
rerunResult,
|
|
useDatabase,
|
|
withConnection,
|
|
type ConsoleExecution,
|
|
type OutputLine,
|
|
type ResultTab,
|
|
} from "./store";
|
|
import styles from "./Database.module.css";
|
|
import { registerTableEditor, tableEditorChanged, type TableEditorHandle } from "./tableEditorFocus";
|
|
import { tx } from "@/platform/i18n";
|
|
|
|
function time(t: number): string {
|
|
const d = new Date(t);
|
|
const p = (n: number, w = 2) => String(n).padStart(w, "0");
|
|
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
|
}
|
|
|
|
function Output() {
|
|
const lines = useDatabase((s) => s.output);
|
|
const ref = useRef<HTMLDivElement>(null);
|
|
useEffect(() => {
|
|
const el = ref.current;
|
|
if (el) el.scrollTop = el.scrollHeight;
|
|
}, [lines.length]);
|
|
return (
|
|
<div className={styles.view}>
|
|
<Toolbar className={styles.toolbar} aria-label="Output actions">
|
|
<span className={styles.spacer} />
|
|
<IconButton icon="trash" title="Clear All" disabled={!lines.length} onClick={clearOutput} />
|
|
</Toolbar>
|
|
<div
|
|
ref={ref}
|
|
className={styles.output}
|
|
tabIndex={0}
|
|
onKeyDown={copySelectionOnKeyDown}
|
|
role="log"
|
|
aria-label={tx("Database output")}
|
|
>
|
|
{lines.map((l: OutputLine) => (
|
|
<div key={l.id} className={clsx(styles.outputLine, l.kind === "error" && styles.outputError)}>
|
|
<span className={styles.outputTime}>[{time(l.time)}]</span>{" "}
|
|
{l.prompt && <span className={styles.outputPrompt}>{l.prompt} </span>}
|
|
<span className={l.kind === "statement" ? styles.outputStatement : undefined}>{l.text}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** The table a query reads (target of exported SQL inserts), else IDEA's placeholder. */
|
|
function queryTable(text: string, data: Pick<ExportData, "driver">): string {
|
|
const a = analyze(text, text.length, data.driver);
|
|
return a.refs.find((r) => r.depth === 0 && r.kind === "table")?.name ?? "MY_TABLE";
|
|
}
|
|
|
|
const PAGE_SIZES = [10, 100, 500, 1000];
|
|
|
|
/** Why a result's grid is read-only, as the issue's examples put it. */
|
|
function readonlyNotice(reason: EditBlockReason): string {
|
|
switch (reason) {
|
|
case "joined":
|
|
return tx("Read-only: the query joins several tables.");
|
|
case "aggregated":
|
|
return tx("Read-only: the result is aggregated (DISTINCT, GROUP BY or an aggregate function).");
|
|
case "setOp":
|
|
return tx("Read-only: the result combines several queries (UNION / INTERSECT / EXCEPT).");
|
|
case "plain":
|
|
return tx("Read-only: the result is not a plain select from a single table.");
|
|
}
|
|
}
|
|
|
|
/** IDEA's pager at the bottom of a result: |< < 1-500 of 501+ > >| and the page size; paging runs the query again. */
|
|
/** The result tab's page position and the page moves it allows, shared by the pager and the `db.*Page` actions. */
|
|
function pagerOf(tab: ResultTab) {
|
|
const r = tab.outcome.result!;
|
|
const page = tab.page ?? 0;
|
|
const pageSize = tab.pageSize ?? Math.max(r.rows.length, 1);
|
|
const state = { page, pageSize, rows: r.rows.length, hasMore: r.hasMore, total: tab.total ?? null };
|
|
const w = pageWindow(state);
|
|
const canPage = pageable(tab) && !tab.busy;
|
|
const go = (p: number, size = pageSize) => void loadResultPage(tab.id, p, size);
|
|
const goLast = async () => {
|
|
let lastPage = w.lastPage;
|
|
if (lastPage === null) {
|
|
const total = await countResult(tab.id);
|
|
if (total === null) return;
|
|
lastPage = pageWindow({ ...state, total }).lastPage;
|
|
}
|
|
if (lastPage !== null && lastPage !== page) go(lastPage);
|
|
};
|
|
return {
|
|
page,
|
|
pageSize,
|
|
w,
|
|
canPage,
|
|
go,
|
|
goLast,
|
|
canPrevious: canPage && page > 0,
|
|
canNext: canPage && r.hasMore,
|
|
canLast: canPage && !((!r.hasMore && w.total !== null) || (w.total === null && !countable(tab))),
|
|
};
|
|
}
|
|
|
|
function Pager({ tab }: { tab: ResultTab }) {
|
|
const { page, pageSize, w, canPage, go, goLast, canPrevious, canNext, canLast } = pagerOf(tab);
|
|
const { first, last } = w;
|
|
const total = w.total === null ? `${w.last + 1}+` : String(w.total);
|
|
const sizes = PAGE_SIZES.includes(pageSize) ? PAGE_SIZES : [...PAGE_SIZES, pageSize].sort((a, b) => a - b);
|
|
const sizeSelect = (label?: string) => (
|
|
<Select
|
|
variant="ghost"
|
|
aria-label="Page size"
|
|
value={String(pageSize)}
|
|
options={sizes.map((v) => ({ value: String(v), label: String(v) }))}
|
|
renderValue={label ? () => label : undefined}
|
|
onChange={(v) => go(0, Number(v))}
|
|
disabled={!canPage}
|
|
/>
|
|
);
|
|
// Everything fits on one page: only the row count, which still sets the page size.
|
|
const count = w.total;
|
|
if (!canPrevious && !canNext && count !== null)
|
|
return (
|
|
<Toolbar className={styles.resultPager} aria-label="Result pages" title={outcomeSummary(tab.outcome)}>
|
|
{sizeSelect(tx`${count} rows`)}
|
|
</Toolbar>
|
|
);
|
|
return (
|
|
<Toolbar className={styles.resultPager} aria-label="Result pages" title={outcomeSummary(tab.outcome)}>
|
|
<IconButton
|
|
icon="page-first"
|
|
title="First Page"
|
|
shortcut={shortcutLabel("db.firstPage")}
|
|
size="small"
|
|
disabled={!canPrevious}
|
|
onClick={() => go(0)}
|
|
/>
|
|
<IconButton
|
|
icon="chevron-left"
|
|
title="Previous Page"
|
|
shortcut={shortcutLabel("db.previousPage")}
|
|
size="small"
|
|
disabled={!canPrevious}
|
|
onClick={() => go(page - 1)}
|
|
/>
|
|
<button
|
|
type="button"
|
|
className={clsx(styles.resultPagerRange, styles.resultPagerCount)}
|
|
disabled={w.total !== null || !canPage || !countable(tab)}
|
|
title={w.total === null ? tx("Count rows") : undefined}
|
|
onClick={() => void countResult(tab.id)}
|
|
>
|
|
{tx`${first}-${last} of ${total}`}
|
|
</button>
|
|
<IconButton
|
|
icon="chevron-right"
|
|
title="Next Page"
|
|
shortcut={shortcutLabel("db.nextPage")}
|
|
size="small"
|
|
disabled={!canNext}
|
|
onClick={() => go(page + 1)}
|
|
/>
|
|
<IconButton
|
|
icon="page-last"
|
|
title="Last Page"
|
|
shortcut={shortcutLabel("db.lastPage")}
|
|
size="small"
|
|
disabled={!canLast}
|
|
onClick={() => void goLast()}
|
|
/>
|
|
{sizeSelect()}
|
|
</Toolbar>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Unsubmitted edits by the rows they were made on, and the results whose edits are being
|
|
* submitted. They live outside the pane, which remounts when another result tab is selected,
|
|
* so a submit that ends while its pane is unmounted still clears what the remounted one shows.
|
|
*/
|
|
const keptEdits = new WeakMap<DbQueryResult, PendingEdits>();
|
|
const submittingResults = new Set<DbQueryResult>();
|
|
const NO_EDITS = emptyEdits();
|
|
const resultListeners = new Set<() => void>();
|
|
function notifyResults() {
|
|
for (const listener of resultListeners) listener();
|
|
}
|
|
function subscribeResults(listener: () => void) {
|
|
resultListeners.add(listener);
|
|
return () => void resultListeners.delete(listener);
|
|
}
|
|
function setKeptEdits(result: DbQueryResult, edits: PendingEdits) {
|
|
if (hasEdits(edits)) keptEdits.set(result, edits);
|
|
else keptEdits.delete(result);
|
|
notifyResults();
|
|
}
|
|
function setSubmittingResult(result: DbQueryResult, on: boolean) {
|
|
if (on) submittingResults.add(result);
|
|
else submittingResults.delete(result);
|
|
notifyResults();
|
|
}
|
|
|
|
/** A result set's toolbar, grid and pager; `onClose` makes it an in-editor result (closed in place, not pinned). */
|
|
export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void }) {
|
|
const [view, setView] = useState<"table" | "chart">("table");
|
|
const [panel, setPanel] = useState<DataPanel | null>(null);
|
|
const [searchOpen, setSearchOpen] = useState(false);
|
|
const [extractor, setExtractor] = useState<ExportFormat>("csv");
|
|
const r = tab.outcome.result;
|
|
const columns = useMemo(() => (r ? r.columns.map((c) => ({ name: c.name, type: c.typeName })) : []), [r]);
|
|
const source = useDatabase((s) => s.sources.find((source) => source.id === splitTarget(tab.sourceId).id));
|
|
const driver = source?.driver ?? "sqlite";
|
|
|
|
// Editing a result in place (like DataGrip): only a plain select of one base
|
|
// table, carrying the table's primary key, on a writable data source.
|
|
const text = tab.outcome.statement.text;
|
|
const editability = useMemo(() => resultEditability(text, driver), [text, driver]);
|
|
const model = useDatabase((s) => s.completion[tab.sourceId]) ?? null;
|
|
const target = useMemo(
|
|
() => (editability.kind === "editable" ? resolveTarget(editability, model, tab.schema) : null),
|
|
[editability, model, tab.schema],
|
|
);
|
|
const detailsId = target ? detailsKey(tab.sourceId, target.schema ?? "", target.table) : null;
|
|
const details = useDatabase((s) => (detailsId ? s.details[detailsId] : undefined));
|
|
const detailsValue = details?.status === "ok" ? details.value : null;
|
|
useEffect(() => {
|
|
// Only when never loaded: a failed fetch must not retry on every state change.
|
|
if (target && !details) void loadDetails(tab.sourceId, target.schema ?? "", target.table);
|
|
}, [target, details, tab.sourceId]);
|
|
const resultNames = useMemo(() => r?.columns.map((c) => c.name) ?? [], [r]);
|
|
const eq = useMemo(
|
|
() =>
|
|
driver === "postgres" || driver === "oracle" || driver === "sqlServer" || driver === "snowflake"
|
|
? (a: string | null | undefined, b: string | null | undefined) => !!a && a === b
|
|
: nameMatcher(driver),
|
|
[driver],
|
|
);
|
|
const sources = useMemo(
|
|
() =>
|
|
editability.kind === "editable"
|
|
? resultColumnSources(editability.items, resultNames, detailsValue?.columns.map((c) => c.name) ?? null, eq)
|
|
: [],
|
|
[editability, resultNames, detailsValue, eq],
|
|
);
|
|
const pk = useMemo(() => {
|
|
if (!detailsValue) return null;
|
|
return pkResultColumns(
|
|
detailsValue.columns.filter((c) => c.primaryKey).map((c) => c.name),
|
|
sources,
|
|
resultNames,
|
|
eq,
|
|
);
|
|
}, [detailsValue, sources, resultNames, eq]);
|
|
// Nullability and defaults follow the table's details once they load (they gate Set NULL / Set DEFAULT).
|
|
const gridColumns = useMemo(
|
|
() =>
|
|
columns.map((c) => {
|
|
const d = detailsValue?.columns.find((x) => eq(x.name, c.name));
|
|
return {
|
|
...c,
|
|
type: d?.dataType ?? c.type,
|
|
primaryKey: !!pk?.includes(c.name),
|
|
nullable: d?.nullable,
|
|
default: d?.default ?? null,
|
|
};
|
|
}),
|
|
[columns, pk, detailsValue, eq],
|
|
);
|
|
const readOnlySource = source?.readOnly ?? false;
|
|
const editable =
|
|
editability.kind === "editable" &&
|
|
!!target &&
|
|
!!pk &&
|
|
!readOnlySource &&
|
|
canModifyTable(driver) &&
|
|
sources.some((s) => s !== null);
|
|
|
|
// The pending edits belong to the result they were made on: fresh rows (a re-run,
|
|
// another page) start over.
|
|
const edits = useSyncExternalStore(subscribeResults, () => (r && keptEdits.get(r)) ?? NO_EDITS);
|
|
const setEdits = (f: (e: PendingEdits) => PendingEdits) => {
|
|
if (r) setKeptEdits(r, f(keptEdits.get(r) ?? NO_EDITS));
|
|
};
|
|
const loaded = r?.rows.length ?? 0;
|
|
const rowCount = loaded + edits.inserts.length;
|
|
// Cells the page carries only the start of are read whole on demand and re-render the grid.
|
|
const wholeCells = useCutCells();
|
|
const value = useCallback(
|
|
(row: number, col: number): Cell => {
|
|
const name = resultNames[col]!;
|
|
if (row >= loaded) return edits.inserts[row - loaded]?.get(name) ?? null;
|
|
const upd = edits.updates.get(row);
|
|
if (upd?.has(name)) return upd.get(name)!;
|
|
return r ? cellOf(r, row, col) : null;
|
|
},
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- `wholeCells` changes when a cut cell is read
|
|
[r, resultNames, loaded, edits, wholeCells],
|
|
);
|
|
const truncated = useCallback(
|
|
(row: number, col: number) => (r && row < loaded ? cutLength(r, row, col) : null),
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- `wholeCells` changes when a cut cell is read
|
|
[r, loaded, wholeCells],
|
|
);
|
|
/** Reads cut cells whole (failing with a notification: `null`). */
|
|
const loadFull = async (cells: ReadonlyArray<{ row: number; col: number }>): Promise<Cell[] | null> => {
|
|
try {
|
|
return await loadCells(tab, cells);
|
|
} catch (e) {
|
|
notifications().notify({
|
|
level: "error",
|
|
title: "Cannot read the whole value",
|
|
body: e instanceof Error ? e.message : String(e),
|
|
key: "db-whole-value",
|
|
});
|
|
return null;
|
|
}
|
|
};
|
|
|
|
const onEdit = (row: number, col: number, v: Cell) => {
|
|
if (!editable || busy || !sources[col]) return; // an aliased or computed column
|
|
const name = resultNames[col]!;
|
|
setEdits((e) => {
|
|
const next: PendingEdits = { updates: new Map(e.updates), deletes: new Set(e.deletes), inserts: [...e.inserts] };
|
|
if (row >= loaded) {
|
|
const ins = new Map(next.inserts[row - loaded]);
|
|
ins.set(name, v);
|
|
next.inserts[row - loaded] = ins;
|
|
} else {
|
|
const upd = new Map(next.updates.get(row));
|
|
if ((r ? cellOf(r, row, col) : null) === v) upd.delete(name);
|
|
else upd.set(name, v);
|
|
if (upd.size) next.updates.set(row, upd);
|
|
else next.updates.delete(row);
|
|
}
|
|
return next;
|
|
});
|
|
};
|
|
|
|
const onResetCell = (row: number, col: number) => {
|
|
setEdits((e) => {
|
|
const inserts = [...e.inserts];
|
|
const ins = new Map(inserts[row - loaded]);
|
|
ins.delete(resultNames[col]!);
|
|
inserts[row - loaded] = ins;
|
|
return { ...e, inserts };
|
|
});
|
|
};
|
|
|
|
const deleteRows = (rows: number[]) =>
|
|
setEdits((e) => {
|
|
const deletes = new Set(e.deletes);
|
|
const insertsGone = new Set(rows.filter((row) => row >= loaded).map((row) => row - loaded));
|
|
for (const row of rows) if (row < loaded) deletes.add(row);
|
|
return { ...e, deletes, inserts: e.inserts.filter((_, i) => !insertsGone.has(i)) };
|
|
});
|
|
|
|
const addRow = () => setEdits((e) => ({ ...e, inserts: [...e.inserts, new Map()] }));
|
|
const restoreRows = (rows: number[]) =>
|
|
setEdits((e) => ({ ...e, deletes: new Set([...e.deletes].filter((d) => !rows.includes(d))) }));
|
|
|
|
const dirty = hasEdits(edits);
|
|
const submitting = useSyncExternalStore(subscribeResults, () => !!r && submittingResults.has(r));
|
|
const busy = submitting || !!tab.busy;
|
|
|
|
const submit = async () => {
|
|
if (!r || !target || !pk || !editable || busy || submittingResults.has(r)) return;
|
|
setSubmittingResult(r, true);
|
|
try {
|
|
// The key of a row identifies it by its whole value.
|
|
const keyCells = [...edits.updates.keys(), ...edits.deletes].flatMap((row) =>
|
|
pk.map((name) => ({ row, col: resultNames.indexOf(name) })).filter((c) => cutLength(r, c.row, c.col) !== null),
|
|
);
|
|
if (keyCells.length) await loadCells(tab, keyCells);
|
|
const list = buildRowEdits(resultNames, rowsOf(r), pk, edits);
|
|
// The Output log shows what the submit is about to change.
|
|
for (const s of editStatements(driver, target.schema ?? "", target.table, list)) log("statement", s);
|
|
const n = await withConnection(tab.sourceId, () =>
|
|
call(commands.dbApplyEdits(tab.sourceId, target.schema ?? "", target.table, list)),
|
|
);
|
|
log("result", `${target.table}: ${n} row(s) changed`);
|
|
notifications().notify({ level: "info", title: `${target.table}: ${n} row(s) changed`, key: "db-submit" });
|
|
// Also when this pane was unmounted meanwhile: the applied edits must not come back.
|
|
setKeptEdits(r, NO_EDITS);
|
|
await rerunResult(tab.id);
|
|
} catch (e) {
|
|
log("error", e instanceof Error ? e.message : String(e));
|
|
notifications().notify({
|
|
level: "error",
|
|
title: "Changes were not submitted",
|
|
body: e instanceof Error ? e.message : String(e),
|
|
key: "db-submit",
|
|
});
|
|
} finally {
|
|
setSubmittingResult(r, false);
|
|
}
|
|
};
|
|
|
|
/** The result to export or copy: the whole values, not the starts the page carries. */
|
|
const exportSource = async (): Promise<ExportData | null> => {
|
|
if (!r) return null;
|
|
if (hasCutCells(r)) {
|
|
try {
|
|
await loadPage(tab);
|
|
} catch (e) {
|
|
notifications().notify({
|
|
level: "error",
|
|
title: "Cannot read the whole values",
|
|
body: e instanceof Error ? e.message : String(e),
|
|
key: "db-whole-value",
|
|
});
|
|
return null;
|
|
}
|
|
}
|
|
return {
|
|
columns: gridColumns.map((c) => ({ name: c.name, type: c.type, primaryKey: c.primaryKey })),
|
|
rows: rowsOf(r),
|
|
driver,
|
|
table: queryTable(text, { driver }),
|
|
};
|
|
};
|
|
const showExport = async (at: { x: number; y: number }) => {
|
|
const data = await exportSource();
|
|
if (data) showContextMenu(at, exportMenu(data, queryTable(text, { driver }), extractor));
|
|
};
|
|
|
|
// Submit / Revert / Go to Column (⌘↩ / ⌥⌘Z / ⌘F12) reach the latest state through the handle, as in the table editor.
|
|
const canSubmit = editable && dirty && !busy;
|
|
const viewRef = useRef<HTMLDivElement>(null);
|
|
const handleRef = useRef<TableEditorHandle>({
|
|
dirty: false,
|
|
submit: () => {},
|
|
revert: () => {},
|
|
showColumns: () => {},
|
|
});
|
|
const [columnsAt, setColumnsAt] = useState<{ x: number; y: number } | null>(null);
|
|
const [revealColumn, setRevealColumn] = useState<{ col: number } | null>(null);
|
|
useLayoutEffect(() => {
|
|
const handle = handleRef.current;
|
|
handle.dirty = canSubmit;
|
|
handle.submit = () => {
|
|
if (canSubmit) void submit();
|
|
};
|
|
handle.revert = () => {
|
|
if (!busy) setEdits(() => emptyEdits());
|
|
};
|
|
handle.showColumns = () => {
|
|
const rect = viewRef.current?.getBoundingClientRect();
|
|
if (view === "table" && rect) setColumnsAt({ x: rect.left + rect.width / 2, y: rect.top + 48 });
|
|
};
|
|
const pager = r ? pagerOf(tab) : null;
|
|
const rowsEditable = editable && !busy && view === "table";
|
|
handle.commands = pager
|
|
? {
|
|
reload: { enabled: () => !busy, run: () => void rerunResult(tab.id) },
|
|
firstPage: { enabled: () => pager.canPrevious, run: () => pager.go(0) },
|
|
previousPage: { enabled: () => pager.canPrevious, run: () => pager.go(pager.page - 1) },
|
|
nextPage: { enabled: () => pager.canNext, run: () => pager.go(pager.page + 1) },
|
|
lastPage: { enabled: () => pager.canLast, run: () => void pager.goLast() },
|
|
addRow: { enabled: () => editable && !busy, run: addRow },
|
|
exportData: {
|
|
enabled: () => true,
|
|
run: () => {
|
|
const rect = viewRef.current?.querySelector("[data-db-export]")?.getBoundingClientRect();
|
|
if (rect) void showExport({ x: rect.left, y: rect.bottom });
|
|
},
|
|
},
|
|
deleteRows: { enabled: (rows) => rowsEditable && rows.length > 0, run: deleteRows },
|
|
restoreRows: {
|
|
enabled: (rows) => rowsEditable && rows.some((row) => edits.deletes.has(row)),
|
|
run: restoreRows,
|
|
},
|
|
}
|
|
: undefined;
|
|
tableEditorChanged(handle);
|
|
});
|
|
const hasResult = !!r;
|
|
useEffect(
|
|
() => (hasResult && viewRef.current ? registerTableEditor(viewRef.current, handleRef.current) : undefined),
|
|
[hasResult],
|
|
);
|
|
|
|
if (!r) return null;
|
|
const tableLabel = target ? `${target.schema ? `${target.schema}.` : ""}${target.table}` : "";
|
|
const tablePkCount = detailsValue?.columns.filter((c) => c.primaryKey).length ?? 0;
|
|
let notice: string | null = null;
|
|
if (!editable) {
|
|
if (driver === "jdbc") notice = tx("Use the query console to change JDBC data.");
|
|
else if (driver === "clickhouse") notice = tx("Use the query console to change ClickHouse data.");
|
|
else if (readOnlySource) notice = tx("Read-only data source.");
|
|
else if (editability.kind === "readonly") notice = readonlyNotice(editability.reason);
|
|
else if (!target) notice = tx("Read-only: the table schema could not be identified in the result database.");
|
|
else if (details?.status === "error" || (detailsValue && tablePkCount > 0))
|
|
// The result exists but doesn't carry every key column (or the keys are unknown).
|
|
notice = tx`Read-only: the result has no primary key of ${tableLabel}.`;
|
|
else if (detailsValue) notice = tx("Read-only: the table has no primary key to identify rows.");
|
|
// else: the table's details are still loading.
|
|
}
|
|
return (
|
|
<div className={styles.view} ref={viewRef} data-db-table-editor="">
|
|
<Toolbar className={styles.toolbar} aria-label="Result actions">
|
|
<IconButton icon="database" title="Table" aria-pressed={view === "table"} onClick={() => setView("table")} />
|
|
<IconButton icon="db-chart" title="Chart" aria-pressed={view === "chart"} onClick={() => setView("chart")} />
|
|
<span className={styles.toolbarSeparator} />
|
|
<IconButton
|
|
icon="refresh"
|
|
title="Rerun Query"
|
|
shortcut={shortcutLabel("db.reloadPage")}
|
|
disabled={busy}
|
|
onClick={() => void rerunResult(tab.id)}
|
|
/>
|
|
{!onClose && <PinButton tab={tab} />}
|
|
{view === "table" && (
|
|
<IconButton
|
|
icon="search"
|
|
title="Search"
|
|
shortcut={shortcutLabel("find.inFile")}
|
|
aria-pressed={searchOpen}
|
|
onClick={() => setSearchOpen(!searchOpen)}
|
|
/>
|
|
)}
|
|
{editable && (
|
|
<>
|
|
<IconButton
|
|
icon="plus"
|
|
title="Add Row"
|
|
shortcut={shortcutLabel("db.addRow")}
|
|
disabled={busy}
|
|
onClick={addRow}
|
|
/>
|
|
<IconButton
|
|
icon="revert"
|
|
title="Revert"
|
|
shortcut={shortcutLabel("db.revertChanges")}
|
|
disabled={!dirty || busy}
|
|
onClick={() => setEdits(() => emptyEdits())}
|
|
/>
|
|
<IconButton
|
|
icon="arrow-up"
|
|
title="Submit"
|
|
shortcut={shortcutLabel("db.submitChanges")}
|
|
disabled={!dirty || busy}
|
|
onClick={() => void submit()}
|
|
/>
|
|
</>
|
|
)}
|
|
{tab.busy && <Spinner size={12} />}
|
|
<span className={styles.spacer} />
|
|
<ExtractorSelect value={extractor} onChange={setExtractor} />
|
|
<IconButton
|
|
icon="export"
|
|
title="Export Data"
|
|
shortcut={shortcutLabel("db.exportData")}
|
|
data-db-export=""
|
|
onClick={(e) => void showExport({ x: e.clientX, y: e.clientY })}
|
|
/>
|
|
{view === "table" && <PanelToggle panel={panel} onChange={setPanel} />}
|
|
{onClose && <IconButton icon="close" title="Close" onClick={onClose} />}
|
|
</Toolbar>
|
|
{view === "chart" ? (
|
|
<div className={styles.fill}>
|
|
<ChartView columns={columns} rows={r.rows} />
|
|
</div>
|
|
) : (
|
|
<>
|
|
{notice && (
|
|
<div className={styles.notice} role="note">
|
|
{notice}
|
|
</div>
|
|
)}
|
|
<div className={styles.fill}>
|
|
<DataView
|
|
columns={gridColumns}
|
|
rowCount={rowCount}
|
|
fixedRows={loaded}
|
|
driver={driver}
|
|
value={value}
|
|
truncated={truncated}
|
|
loadFull={loadFull}
|
|
panel={panel}
|
|
onPanelChange={setPanel}
|
|
copyFormat={copyFormatOf(extractor)}
|
|
extractor={{ value: extractor, onChange: setExtractor, table: exportSource }}
|
|
searchOpen={searchOpen}
|
|
onSearchOpenChange={setSearchOpen}
|
|
firstRowNumber={(tab.page ?? 0) * (tab.pageSize ?? 0) + 1}
|
|
pager={<Pager tab={busy ? { ...tab, busy: true } : tab} />}
|
|
aria-label={tab.title}
|
|
rowState={(row) => (row >= loaded ? "inserted" : edits.deletes.has(row) ? "deleted" : null)}
|
|
isModified={(row, col) => !!edits.updates.get(row)?.has(resultNames[col]!)}
|
|
editable={editable && !busy}
|
|
onEdit={onEdit}
|
|
onResetCell={onResetCell}
|
|
revealColumn={revealColumn}
|
|
rowMenu={(rows) =>
|
|
editable && !busy
|
|
? [
|
|
{
|
|
kind: "action",
|
|
action: "db.deleteRows",
|
|
icon: "trash",
|
|
arg: { rows, editor: handleRef.current },
|
|
},
|
|
{ kind: "action", action: "db.restoreRows", arg: { rows, editor: handleRef.current } },
|
|
]
|
|
: []
|
|
}
|
|
/>
|
|
</div>
|
|
</>
|
|
)}
|
|
{columnsAt && (
|
|
<ColumnsPopup
|
|
anchor={columnsAt}
|
|
table={tableLabel || tab.title}
|
|
columns={columns}
|
|
onPick={(col) => {
|
|
setColumnsAt(null);
|
|
setRevealColumn({ col });
|
|
}}
|
|
onClose={() => setColumnsAt(null)}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
interface PlanRow {
|
|
node: DbPlanNode;
|
|
index: number;
|
|
key: string;
|
|
}
|
|
|
|
/** IDEA's operation icons: a table for scans of one, a key for index lookups, an arrow for the statement. */
|
|
function planIcon(r: PlanRow): string | null {
|
|
if (r.index < 0) return "arrow-left";
|
|
if (/index/i.test(r.node.operation)) return "db-key";
|
|
if (/scan/i.test(r.node.operation)) return "db-table";
|
|
return null;
|
|
}
|
|
|
|
/** IDEA's Query Plan tab: the operation tree with its parameters, the selected operation's properties beside it. */
|
|
function PlanResult({ tab }: { tab: ResultTab }) {
|
|
const plan = useMemo(() => tab.plan ?? [], [tab.plan]);
|
|
const rows = useMemo(() => plan.map((node, index): PlanRow => ({ node, index, key: String(index) })), [plan]);
|
|
// IDEA roots the operations in the statement itself ("Select").
|
|
const statement = useMemo((): PlanRow => {
|
|
const kind = /^\s*(\w+)/.exec(tab.outcome.statement.text)?.[1]?.toLowerCase() ?? "statement";
|
|
const operation = kind[0]!.toUpperCase() + kind.slice(1);
|
|
return {
|
|
node: { parent: null, operation, params: "", properties: [{ name: "Operation", value: kind }] },
|
|
index: -1,
|
|
key: "statement",
|
|
};
|
|
}, [tab.outcome.statement.text]);
|
|
const [selected, setSelected] = useState(-1);
|
|
// Everything starts expanded, a re-explained plan too.
|
|
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
|
|
const keys = useMemo(() => [statement.key, ...rows.map((r) => r.key)], [statement, rows]);
|
|
const expanded = useMemo(() => new Set(keys.filter((k) => !collapsed.has(k))), [keys, collapsed]);
|
|
const setExpanded = (next: ReadonlySet<string>) => setCollapsed(new Set(keys.filter((k) => !next.has(k))));
|
|
const children = (r: PlanRow) =>
|
|
r === statement ? rows.filter((c) => c.node.parent === null) : rows.filter((c) => c.node.parent === r.index);
|
|
const props = (selected < 0 ? statement : rows[selected])?.node.properties ?? [];
|
|
const selectedKey = selected < 0 ? statement.key : String(selected);
|
|
return (
|
|
<div className={styles.view}>
|
|
<Toolbar className={styles.toolbar} aria-label="Result actions">
|
|
<IconButton icon="refresh" title="Explain Again" disabled={tab.busy} onClick={() => void rerunResult(tab.id)} />
|
|
<PinButton tab={tab} />
|
|
{tab.busy && <Spinner size={12} />}
|
|
</Toolbar>
|
|
<div className={clsx(styles.fill, styles.planView)}>
|
|
<div className={styles.planTree}>
|
|
<div className={styles.planHeader}>
|
|
<span>
|
|
<T>Operation</T>
|
|
</span>
|
|
<span>
|
|
<T>Params</T>
|
|
</span>
|
|
</div>
|
|
{plan.length ? (
|
|
<Tree<PlanRow>
|
|
aria-label="Query plan"
|
|
roots={[statement]}
|
|
selected={new Set([selectedKey])}
|
|
expanded={expanded}
|
|
onExpandedChange={setExpanded}
|
|
getKey={(r) => r.key}
|
|
getLabel={(r) => r.node.operation}
|
|
getChildren={(r) => children(r)}
|
|
isExpandable={(r) => children(r).length > 0}
|
|
onSelectionChange={(_, lead) => lead && setSelected(lead.index)}
|
|
renderNode={(r) => (
|
|
<span className={styles.planRow}>
|
|
<span className={styles.planOperation}>
|
|
{planIcon(r) && <Icon name={planIcon(r)!} size={16} />}
|
|
{r.node.operation}
|
|
</span>
|
|
<span className={styles.planParams}>{r.node.params}</span>
|
|
</span>
|
|
)}
|
|
/>
|
|
) : (
|
|
<EmptyState title="Empty plan" />
|
|
)}
|
|
</div>
|
|
<table className={styles.planProperties} aria-label={tx("Plan node properties")}>
|
|
<thead>
|
|
<tr>
|
|
<th>
|
|
<T>Property</T>
|
|
</th>
|
|
<th>
|
|
<T>Value</T>
|
|
</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{props.map((p) => (
|
|
<tr key={p.name}>
|
|
<td>{p.name}</td>
|
|
<td>{p.value}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** IDEA's Pin Tab: the console's next runs leave this result alone. */
|
|
function PinButton({ tab }: { tab: ResultTab }) {
|
|
return (
|
|
<IconButton icon="pin" title="Pin Tab" aria-pressed={!!tab.pinned} onClick={() => pinResult(tab.id, !tab.pinned)} />
|
|
);
|
|
}
|
|
|
|
/** The most recently started console request, while it runs. */
|
|
function useLatestExecution(): [string, ConsoleExecution] | undefined {
|
|
return useDatabase(
|
|
useShallow((s) => {
|
|
let latest: [string, ConsoleExecution] | undefined;
|
|
for (const entry of Object.entries(s.executions))
|
|
if (!latest || entry[1].startedAt > latest[1].startedAt) latest = entry;
|
|
return latest;
|
|
}),
|
|
);
|
|
}
|
|
|
|
function ExecutingBar({ path, execution }: { path: string; execution: ConsoleExecution }) {
|
|
const startedAt = execution.active?.startedAt ?? execution.startedAt;
|
|
const [now, setNow] = useState(() => Date.now());
|
|
useEffect(() => {
|
|
const timer = setInterval(() => setNow(Date.now()), 100);
|
|
return () => clearInterval(timer);
|
|
}, [startedAt]);
|
|
const name = basename(path);
|
|
const count = execution.statements;
|
|
const index = execution.active ? execution.active.index + 1 : null;
|
|
const label =
|
|
count === 1
|
|
? tx`Executing in ${name}…`
|
|
: index === null
|
|
? tx`Executing ${count} statements in ${name}…`
|
|
: tx`Executing statement ${index} of ${count} in ${name}…`;
|
|
return (
|
|
<div className={styles.executing} role="status">
|
|
<Spinner size={12} label={tx("Executing")} />
|
|
<span className={styles.executingText} title={path}>
|
|
{label}
|
|
</span>
|
|
<span className={styles.executingTime}>{formatElapsed(Math.max(0, now - startedAt))}</span>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function ResultsView() {
|
|
const results = useDatabase((s) => s.results);
|
|
const execution = useLatestExecution();
|
|
const active = useDatabase((s) => s.activeResult);
|
|
const hasOutput = useDatabase((s) => s.output.length > 0);
|
|
const root = useRef<HTMLDivElement>(null);
|
|
const panel = useRef<HTMLDivElement>(null);
|
|
/** Tab from a result tab: its table, plan tree or output log (IDEA focuses the tab's content). */
|
|
const focusContent = () => {
|
|
const target = panel.current?.querySelector<HTMLElement>('[role="grid"], [role="tree"], [role="log"]');
|
|
target?.focus();
|
|
return !!target && document.activeElement === target;
|
|
};
|
|
useEffect(() => {
|
|
const syncFocus = () => setContext("dbResultsFocus", !!root.current?.contains(document.activeElement));
|
|
document.addEventListener("focusin", syncFocus);
|
|
syncFocus();
|
|
return () => {
|
|
document.removeEventListener("focusin", syncFocus);
|
|
setContext("dbResultsFocus", false);
|
|
};
|
|
}, []);
|
|
const tabMenu = (id: string, e: MouseEvent) => {
|
|
e.preventDefault();
|
|
const rect = e.currentTarget.getBoundingClientRect();
|
|
showContextMenu(e.clientX || e.clientY ? e : { x: rect.left, y: rect.bottom }, resultTabMenu(Number(id)), {
|
|
owner: e.currentTarget,
|
|
});
|
|
};
|
|
const executing = execution && <ExecutingBar path={execution[0]} execution={execution[1]} />;
|
|
if (!results.length && !hasOutput && executing) return <div className={styles.view}>{executing}</div>;
|
|
if (!results.length && !hasOutput)
|
|
return (
|
|
<EmptyState title="No results">
|
|
<T>Execute a statement in a query console with ⌘↩.</T>
|
|
</EmptyState>
|
|
);
|
|
const tab = results.find((r) => r.id === active);
|
|
return (
|
|
<div
|
|
ref={root}
|
|
className={styles.view}
|
|
data-focus-scope=""
|
|
onKeyDown={(e) => {
|
|
if (e.key !== "ContextMenu" && !(e.shiftKey && e.key === "F10")) return;
|
|
const tab = (e.target as Element).closest<HTMLElement>('[role="tab"]');
|
|
if (!tab?.id.startsWith("db-results-tab-")) return;
|
|
e.preventDefault();
|
|
const rect = tab.getBoundingClientRect();
|
|
showContextMenu(
|
|
{ x: rect.left, y: rect.bottom },
|
|
resultTabMenu(Number(tab.id.slice("db-results-tab-".length))),
|
|
{ owner: tab.parentElement },
|
|
);
|
|
}}
|
|
>
|
|
<ToolWindowContentTabs>
|
|
<Tabs
|
|
className={styles.resultTabs}
|
|
variant="compact"
|
|
aria-label="Results"
|
|
activeId={tab ? String(tab.id) : String(OUTPUT_TAB)}
|
|
panelIdPrefix="db-results"
|
|
focusContent={focusContent}
|
|
onSelect={(id) => useDatabase.setState({ activeResult: Number(id) })}
|
|
onClose={(id) => closeResult(Number(id))}
|
|
onTogglePin={(id) => {
|
|
const r = results.find((r) => r.id === Number(id));
|
|
if (r) pinResult(r.id, !r.pinned);
|
|
}}
|
|
onContextMenu={tabMenu}
|
|
items={[
|
|
{ id: String(OUTPUT_TAB), label: "Output", icon: "db-console", closable: false },
|
|
...results.map((r) => ({
|
|
id: String(r.id),
|
|
label: r.title,
|
|
verbatim: true,
|
|
icon: r.plan ? "db-plan" : "db-table",
|
|
closable: true,
|
|
pinned: r.pinned,
|
|
tooltip: r.outcome.statement.text,
|
|
})),
|
|
]}
|
|
/>
|
|
</ToolWindowContentTabs>
|
|
{executing}
|
|
<div
|
|
ref={panel}
|
|
className={styles.fill}
|
|
role="tabpanel"
|
|
id={`db-results-panel-${tab ? tab.id : OUTPUT_TAB}`}
|
|
aria-labelledby={`db-results-tab-${tab ? tab.id : OUTPUT_TAB}`}
|
|
>
|
|
{!tab ? <Output /> : tab.plan ? <PlanResult key={tab.id} tab={tab} /> : <Result key={tab.id} tab={tab} />}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|