feat(database): add a Database Output tool window for SQL consoles (#6243)

SQL consoles and files get a Database Output bottom tool window. It follows the active editor, keeps result tabs and errors scoped to each console, and has a client selector (file name with its data source) for looking at another run, plus a button to open that client in its editor. Run and Explain reveal the current client's results while keeping editor focus; background completions and late Explain responses leave the selected client in view. Switching clients or destinations never re-runs SQL. Settings > Tools > Database can send results to Services instead.

Closes #6176

Co-authored-by: principalwater <[email protected]>
Цей коміт міститься в:
Vladislav Kuzmin authored and GitHub committed 2026-11-28 08:56:19 +08:00
1 джерело 45f6366b92
коміт c04d9381be
20 files changed
+867 -146

No files matched your search

+13
Переглянути файл
@@ -2002,6 +2002,19 @@ mod tests {
assert_eq!(json["appearance"]["smoothScrolling"], false);
}
#[test]
fn database_output_destination_defaults_and_round_trips() {
let old: Settings = serde_json::from_str(r#"{"database":{"inEditorResults":true}}"#).unwrap();
assert_eq!(old.database.output_destination, DatabaseOutputDestination::DatabaseOutput);
assert!(old.database.in_editor_results);
let services: Settings = serde_json::from_str(r#"{"database":{"outputDestination":"services"}}"#).unwrap();
assert_eq!(services.database.output_destination, DatabaseOutputDestination::Services);
let saved = serde_json::to_value(&services).unwrap();
assert_eq!(saved["database"]["outputDestination"], "services");
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().database, services.database);
}
#[test]
fn window_close_settings_default_off_and_round_trip() {
for old in [r#"{}"#, r#"{"general":{"confirmExit":false}}"#] {
+12 -1
Переглянути файл
@@ -405,13 +405,24 @@ impl Default for LogLevelColors {
#[serde(default, rename_all = "camelCase")]
pub struct DatabaseSettings {
/// A console's result sets show under the statements that produced them, in the editor,
/// instead of in the Services view's result tabs.
/// instead of in the output window's result tabs.
pub in_editor_results: bool,
/// The tool window that receives SQL query output and plans.
pub output_destination: DatabaseOutputDestination,
/// Languages & Frameworks › SQL Resolution Scopes: the data source SQL in a file or folder
/// resolves against (completion, inspections, navigation), most specific path first.
pub resolution_scopes: Vec<SqlResolutionScope>,
}
/// Database › Query Output: where SQL results open.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DatabaseOutputDestination {
#[default]
DatabaseOutput,
Services,
}
/// One row of SQL Resolution Scopes.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
+3 -1
Переглянути файл
@@ -153,7 +153,9 @@ SQL completion knows the connected schema: tables after `FROM`/`JOIN` (with join
## Results and data editing
Results appear in the **Services** tool window under the **Database** tab: an **Output** tab logs every statement, and each result set gets a **Result N** tab (up to 12, pinned tabs excepted).
Query results open in **Database Output** without taking focus from the editor. The window follows the active SQL console or file. Use the **SQL client** selector to inspect another client's output, results or query plans. The selector includes the data source when available. Choose **Open Client in Editor** to focus the selected file. Running or explaining a query in the active editor returns the window to that client.
**Output** logs the client's statements and errors. Each result set gets a **Result N** tab (up to 12, pinned tabs excepted). To return to the **Database** tab in **Services**, change **Settings** → **Tools** → **Database** → **Show query results in**. Switching windows or clients keeps the results and pending grid edits.
Running a console again replaces its previous results: its unpinned result tabs make way for the new run, which gets one tab per result set (**Result N**, or **Result N**, **Result N-2**, … when several selected statements return rows). A run with no result sets, such as an `UPDATE`, keeps the previous results. Results from other consoles stay.
+3 -1
Переглянути файл
@@ -153,7 +153,9 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外
## 结果与数据编辑
结果显示在 **服务** 工具窗口的 **数据库** 标签页中:**输出** 标签页记录每条语句,每个结果集一个 **Result N** 标签页(最多 12 个,已固定的标签页除外)。
查询结果在 **数据库输出** 工具窗口中打开,焦点保留在编辑器。该窗口跟随当前的 SQL 控制台或文件。使用 **SQL 客户端** 选择器查看其他客户端的输出、结果和查询计划。选择器会在有数据源时显示其名称。点击 **在编辑器中打开客户端**,可在编辑器中聚焦所选文件。在当前编辑器运行查询或查看查询计划时,窗口会切回该客户端。
**输出** 记录当前客户端的语句和错误。每个结果集对应一个 **Result N** 标签页(最多 12 个,已固定的标签页除外)。要恢复在 **服务** 的 **数据库** 标签页中显示结果,请在 **设置** → **工具** → **数据库** 中更改 **显示查询结果的位置**。切换窗口或客户端会保留查询结果和待提交的表格修改。
再次运行控制台会替换它之前的结果:它未固定的结果标签页会让位给新的运行,新运行每个结果集一个标签页(**Result N**;选中的多条语句都返回行时为 **Result N**、**Result N-2**……)。没有结果集的运行(如 `UPDATE`)会保留之前的结果。其他控制台的结果不受影响。
+307
Переглянути файл
@@ -0,0 +1,307 @@
import type { EditorView } from "@codemirror/view";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const alpha = "/dev/acme-api/inventory/console.sql";
const beta = "/dev/acme-api/retail/console.sql";
const empty = "/dev/acme-api/empty.sql";
test("follows the active SQL console and preserves the selected client when another query finishes", async ({
workbench: page,
}, info) => {
await stubDesktop(page);
await page.evaluate(
async ({ alpha, beta, empty }) => {
let release: (() => void) | undefined;
const projectPath = "/src/platform/project.ts";
const storePath = "/src/features/database/store.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const { bindConsole, useDatabase } = await import(/* @vite-ignore */ storePath);
useProject.setState({ settings: {} });
useDatabase.setState({
loaded: true,
sources: [
{ id: "inventory", name: "Inventory SQLite", driver: "sqlite", readOnly: true },
{ id: "retail", name: "Retail SQLite", driver: "sqlite", readOnly: true },
],
completion: {
inventory: { defaultSchema: "main", tables: [], foreignKeys: [] },
retail: { defaultSchema: "main", tables: [], foreignKeys: [] },
},
});
bindConsole(alpha, "inventory");
bindConsole(beta, "retail");
bindConsole(empty, "inventory");
Object.assign(window.__ipc.handlers, {
settings_get: () => useProject.getState().settings,
settings_get_global: () => useProject.getState().settings,
settings_set: ({ value }: { value: string }) => ({
database: { outputDestination: JSON.parse(value) },
}),
db_explain: () => [{ parent: null, operation: "Constant row", params: "", properties: [] }],
db_connected: () => ["inventory", "retail"],
db_statements: ({ text }: { text: string }) => [{ from: 0, to: text.length, text }],
db_execute: async ({ statements }: { statements: Array<{ text: string }> }) => {
const statement = statements[0]!;
const text = statement.text;
if (text.includes("Background failure")) {
await new Promise<void>((resolve) => (release = resolve));
return [{ statement, error: "Background failure", result: null }];
}
return [
{
statement,
result: {
columns: [{ name: "value", typeName: "text" }],
rows: [[text.includes("Alpha") ? "Alpha row" : "Beta row"]],
hasMore: false,
elapsedMs: 2,
executionMs: 1,
},
error: null,
},
];
},
"test:finishDbRequest": () => release?.(),
});
},
{ alpha, beta, empty },
);
const open = async (path: string) =>
page.evaluate(async (path) => {
const contributionsPath = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ contributionsPath);
await editorService().openFile(path, { focus: true });
}, path);
const run = async (path: string, sql: string) => {
await open(path);
const editor = page.locator(".cm-editor:visible .cm-content[contenteditable=true]");
await editor.click();
await editor.press("Meta+A");
await page.keyboard.insertText(sql);
await editor.press("Meta+Enter");
await expect(editor).toBeFocused();
};
const panel = page.locator('section[aria-label="Database Output"]');
await run(alpha, "select 'Alpha'");
await expect(panel.getByRole("gridcell", { name: "Alpha row", exact: true })).toBeVisible();
await run(beta, "select 'Beta'");
await expect(panel.getByRole("gridcell", { name: "Beta row", exact: true })).toBeVisible();
await open(alpha);
await expect(panel.getByRole("gridcell", { name: "Alpha row", exact: true })).toBeVisible();
await page.screenshot({ path: info.outputPath("database-output-after.png"), animations: "disabled" });
const client = panel.getByRole("button", { name: "SQL client", exact: true });
await client.click();
await expect(page.getByRole("option", { name: /console\.sql · Inventory SQLite/ })).toBeVisible();
await expect(page.getByRole("option", { name: /console\.sql · Retail SQLite/ })).toBeVisible();
await page.screenshot({ path: info.outputPath("database-output-clients.png"), animations: "disabled" });
await page.getByRole("option", { name: /console\.sql · Retail SQLite/ }).click();
await expect(client).toHaveText("console.sql · Retail SQLite");
await expect(panel.getByRole("gridcell", { name: "Beta row", exact: true })).toBeVisible();
await panel.getByRole("button", { name: "Open Client in Editor" }).click();
const editor = page.locator(".cm-editor:visible .cm-content[contenteditable=true]");
const consoleText = () =>
editor.evaluate((el) =>
(el as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view.state.doc.toString().trimEnd(),
);
await expect(editor).toBeFocused();
await expect.poll(consoleText).toBe("select 'Beta'");
expect(await ipcCalls(page, "db_execute")).toHaveLength(2);
await open(alpha);
const retail = page.getByRole("option", { name: /console\.sql · Retail SQLite/ });
await client.press("ArrowDown");
await expect(retail).toBeVisible();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expect(client).toHaveText("console.sql · Retail SQLite");
await client.press("ArrowDown");
await expect(retail).toBeVisible();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Escape");
await expect(retail).toBeHidden();
await expect(client).toHaveText("console.sql · Retail SQLite");
await client.press("Escape");
await expect(editor).toBeFocused();
await expect.poll(consoleText).toBe("select 'Alpha'");
await expect(client).toHaveText("console.sql · Retail SQLite");
await expect(panel.getByRole("gridcell", { name: "Beta row", exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_execute")).toHaveLength(2);
await editor.press("Meta+A");
await page.keyboard.insertText("select 'Alpha while inspecting Beta'");
await editor.press("Meta+Enter");
await expect(editor).toBeFocused();
await expect(client).toHaveText("console.sql · Inventory SQLite");
await expect(panel.getByRole("gridcell", { name: "Alpha row", exact: true })).toBeVisible();
await page.screenshot({ path: info.outputPath("database-output-foreground-after.png"), animations: "disabled" });
await run(alpha, "select 'Background failure'");
await expect.poll(async () => (await ipcCalls(page, "db_execute")).length).toBe(4);
await client.click();
await retail.click();
await page.evaluate(() => window.__ipc.handlers["test:finishDbRequest"]?.({}));
await expect
.poll(() =>
page.evaluate(async (path) => {
const storePath = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ storePath);
return Object.hasOwn(useDatabase.getState().executions, path);
}, alpha),
)
.toBe(false);
await expect(client).toHaveText("console.sql · Retail SQLite");
await expect(panel.getByRole("gridcell", { name: "Beta row", exact: true })).toBeVisible();
await client.click();
await page.getByRole("option", { name: /console\.sql · Inventory SQLite/ }).click();
await expect(panel.getByRole("log")).toContainText("Background failure");
await expect(panel.getByRole("log")).not.toContainText("select 'Beta'");
await open(empty);
await expect(panel.getByRole("log")).toBeVisible();
await expect(panel.getByRole("log")).not.toContainText("Background failure");
await open(beta);
await client.click();
await page.getByRole("option", { name: /console\.sql · Inventory SQLite/ }).click();
await expect(panel.getByRole("log")).toContainText("Background failure");
await page.getByRole("button", { name: "Explain Plan", exact: true }).click();
await expect(panel.getByRole("tab", { name: "Query Plan" })).toHaveAttribute("aria-selected", "true");
await expect(panel.getByRole("tree")).toContainText("Constant row");
await expect(page.locator(".cm-editor:visible .cm-content[contenteditable=true]")).toBeFocused();
await panel.getByRole("tab", { name: "Query Plan" }).focus();
await page.keyboard.press("Meta+Shift+BracketLeft");
await expect(panel.getByRole("gridcell", { name: "Beta row", exact: true })).toBeVisible();
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("textbox", { name: "Search settings" }).fill("Show query results in");
await settings.getByRole("treeitem", { name: "Database", exact: true }).click();
const destination = settings.getByRole("button", { name: "Show query results in", exact: true });
await expect(destination).toHaveText("Database Output");
await destination.click();
await page.getByRole("option", { name: "Services", exact: true }).click();
await settings.getByRole("button", { name: "OK", exact: true }).click();
expect(await ipcCalls(page, "settings_set")).toContainEqual({
scope: "global",
key: "database.outputDestination",
value: '"services"',
});
const services = page.locator('section[aria-label="Services"]');
await expect(services).toBeVisible();
await expect(services.getByRole("tab", { name: "Query Plan" })).toBeVisible();
await expect(panel).not.toBeVisible();
expect(await ipcCalls(page, "db_execute")).toHaveLength(4);
});
for (const failed of [false, true]) {
test(`keeps a newer result selected when an older Explain ${failed ? "fails" : "finishes"}`, async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
let finish: ((fail: boolean) => void) | undefined;
const projectPath = "/src/platform/project.ts";
const storePath = "/src/features/database/store.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const { useDatabase } = await import(/* @vite-ignore */ storePath);
useProject.setState({ settings: {} });
useDatabase.setState({
loaded: true,
sources: [{ id: "db", name: "Demo SQLite", driver: "sqlite", readOnly: true }],
completion: { db: { defaultSchema: "main", tables: [], foreignKeys: [] } },
});
Object.assign(window.__ipc.handlers, {
db_connected: () => ["db"],
db_statements: ({ text }: { text: string }) => [{ from: 0, to: text.length, text }],
db_explain: () =>
new Promise((resolve, reject) => {
finish = (fail) => {
if (fail) reject(new Error("Delayed explain failure"));
else resolve([{ parent: null, operation: "Delayed scan", params: "", properties: [] }]);
};
}),
db_execute: ({ statements }: { statements: Array<{ text: string }> }) => [
{
statement: statements[0],
result: {
columns: [{ name: "value", typeName: "text" }],
rows: [[statements[0]!.text]],
hasMore: false,
elapsedMs: 2,
executionMs: 1,
},
error: null,
},
],
"test:finishExplain": ({ fail }: { fail: boolean }) => finish?.(fail),
});
});
const open = (path: string) =>
page.evaluate(async (path) => {
const contributionsPath = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ contributionsPath);
await editorService().openFile(path, { focus: true });
}, path);
const editor = page.locator(".cm-editor:visible .cm-content[contenteditable=true]");
const edit = async (sql: string) => {
await editor.click();
await editor.press("Meta+A");
await page.keyboard.insertText(sql);
};
const panel = page.locator('section[aria-label="Database Output"]');
await open(beta);
await edit("select 'Beta'");
await editor.press("Meta+Enter");
await expect(panel.getByRole("gridcell", { name: "select 'Beta'", exact: true })).toBeVisible();
await open(alpha);
await edit("select 'Older plan'");
await page.getByRole("button", { name: "Explain Plan", exact: true }).click();
await expect.poll(async () => (await ipcCalls(page, "db_explain")).length).toBe(1);
await edit("select 'Newer run'");
await editor.press("Meta+Enter");
const result = panel.getByRole("gridcell", { name: "select 'Newer run'", exact: true });
await expect(result).toBeVisible();
await expect(editor).toBeFocused();
if (failed) await open(beta);
await page.evaluate((fail) => window.__ipc.handlers["test:finishExplain"]?.({ fail }), failed);
const plan = panel.getByRole("tab", { name: "Query Plan", exact: true });
if (failed) {
await expect
.poll(() =>
page.evaluate(async (path) => {
const storePath = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ storePath);
return useDatabase
.getState()
.output.some(
(line: { path?: string; text: string }) =>
line.path === path && line.text.includes("Delayed explain failure"),
);
}, alpha),
)
.toBe(true);
await expect(panel.getByRole("gridcell", { name: "select 'Beta'", exact: true })).toBeVisible();
await expect(editor).toBeFocused();
await open(alpha);
} else {
await expect(plan).toBeVisible();
}
await expect(result).toBeVisible();
await expect(editor).toBeFocused();
if (failed) {
await panel.getByRole("tab", { name: "Output", exact: true }).click();
await expect(panel.getByRole("log")).toContainText("Delayed explain failure");
} else {
await plan.click();
await expect(panel.getByRole("tree")).toContainText("Delayed scan");
}
expect(await ipcCalls(page, "db_execute")).toHaveLength(2);
});
}
+3
Переглянути файл
@@ -44,6 +44,9 @@ async function seedResults(page: Page, edge = false) {
async ({ edge, edgeTitle, bindings }) => {
const storePath = "/src/features/database/store.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(projectPath);
useProject.setState({ settings: { database: { outputDestination: "services" } } });
const { useDatabase, RESULTS_VIEW } = await import(storePath);
const { showServiceView } = await import(contributionsPath);
useDatabase.setState({
+6 -1
Переглянути файл
@@ -5386,13 +5386,18 @@ export type DataSource_Serialize = {
pluginSourceId?: string | null,
};
/** Database › Query Output: where SQL results open. */
export type DatabaseOutputDestination = "databaseOutput" | "services";
/** Database settings: Query Execution and SQL Resolution Scopes. */
export type DatabaseSettings = {
/**
* A console's result sets show under the statements that produced them, in the editor,
* instead of in the Services view's result tabs.
* instead of in the output window's result tabs.
*/
inEditorResults?: boolean,
/** The tool window that receives SQL query output and plans. */
outputDestination?: DatabaseOutputDestination,
/**
* Languages & Frameworks › SQL Resolution Scopes: the data source SQL in a file or folder
* resolves against (completion, inspections, navigation), most specific path first.
+15
Переглянути файл
@@ -158,6 +158,21 @@
.resultTabs {
padding-inline: var(--space-2);
}
.outputStrip {
display: flex;
align-items: center;
gap: var(--space-1);
padding-inline-start: var(--space-2);
min-width: 0;
}
.outputStrip .resultTabs {
flex: 1;
min-width: 0;
}
.outputClient {
max-width: 40%;
flex: none;
}
.toolbar {
display: flex;
align-items: center;
+98
Переглянути файл
@@ -0,0 +1,98 @@
import { useEffect, useState } from "react";
import { useShallow } from "zustand/react/shallow";
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { basename } from "@/platform/project";
import { IconButton, Select } from "@/ui";
import { editorService } from "@/workbench/contributions";
import { onOutputReveal } from "./outputDestination";
import { ResultsContent } from "./ResultsView";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { consoleSource, sourceById, targetLabel, useDatabase } from "./store";
import styles from "./Database.module.css";
function sqlPath(active: TextEditorHandle | null) {
const ctx = active?.ctx;
return ctx?.language === SQL_LANGUAGE && !ctx.virtual ? ctx.path : null;
}
export function DatabaseOutput() {
const [{ editor, manual }, setClient] = useState(() => ({
editor: sqlPath(useEditorRegistry.getState().active),
manual: null as string | null,
}));
useEffect(() => {
const followEditor = useEditorRegistry.subscribe(({ active }) => {
const path = sqlPath(active);
if (path) setClient((prev) => (prev.editor === path ? prev : { editor: path, manual: null }));
});
const followReveal = onOutputReveal((path) => {
// Parsing may have finished after the user switched editors.
if (sqlPath(useEditorRegistry.getState().active) === path) setClient({ editor: path, manual: null });
});
return () => {
followEditor();
followReveal();
};
}, []);
const clients = useDatabase(
useShallow((s) => [
...new Set([
...s.results.map((tab) => tab.path),
...s.output.flatMap((line) => (line.path ? [line.path] : [])),
...Object.keys(s.executions),
]),
]),
);
const path = manual ?? editor ?? clients.at(-1) ?? null;
const paths = [...new Set(path ? [path, ...clients] : clients)];
const labels = useDatabase(
useShallow(() =>
paths.map((value) => {
const target = consoleSource(value);
const name = basename(value);
return target && sourceById(target) ? `${name} · ${targetLabel(target)}` : name;
}),
),
);
const choices = paths.map((value, index) => {
const label = labels[index]!;
return {
value,
label: labels.indexOf(label) === labels.lastIndexOf(label) ? label : value,
detail: value,
verbatim: true,
verbatimDetail: true,
};
});
return (
<ResultsContent
path={path ?? ""}
clientSelector={
<>
<Select
aria-label={tx("SQL client")}
placeholder="No SQL client"
variant="ghost"
className={styles.outputClient}
options={choices}
value={path}
disabled={!choices.length}
searchable
onChange={(path) => setClient((prev) => ({ ...prev, manual: path }))}
/>
<IconButton
icon="edit-source"
title="Open Client in Editor"
size="small"
disabled={!path}
onClick={() => {
if (path) void editorService().openFile(path, { focus: true });
}}
/>
</>
}
/>
);
}
+80 -54
Переглянути файл
@@ -1,7 +1,6 @@
/**
* 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.
* SQL output and result tabs, shared by Database Output and Services.
* Results carry their own grids, plans, and pending data edits.
*/
import { canModifyTable } from "./objects";
import { copySelectionOnKeyDown } from "@/ui/selectableText";
@@ -14,6 +13,7 @@ import {
useState,
useSyncExternalStore,
type MouseEvent,
type ReactNode,
} from "react";
import clsx from "clsx";
import { useShallow } from "zustand/react/shallow";
@@ -53,6 +53,9 @@ import { analyze } from "./sql/analyze";
import { nameMatcher } from "./sql/dialect";
import {
OUTPUT_TAB,
activeResultFor,
resultsFor,
selectResult,
clearOutput,
closeResult,
countResult,
@@ -81,18 +84,20 @@ function time(t: number): string {
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);
function Output({ path }: { path?: string }) {
const lines = useDatabase(
useShallow((s) => (path === undefined ? s.output : s.output.filter((line) => line.path === path))),
);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = ref.current;
if (el) el.scrollTop = el.scrollHeight;
}, [lines.length]);
}, [lines.length, path]);
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} />
<IconButton icon="trash" title="Clear All" disabled={!lines.length} onClick={() => clearOutput(path)} />
</Toolbar>
<div
ref={ref}
@@ -440,17 +445,18 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
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);
for (const s of editStatements(driver, target.schema ?? "", target.table, list))
log("statement", s, undefined, tab.path);
const n = await withConnection(tab.sourceId, () =>
call(commands.dbApplyEdits(tab.sourceId, target.schema ?? "", target.table, list)),
);
log("result", `${target.table}: ${n} row(s) changed`);
log("result", `${target.table}: ${n} row(s) changed`, undefined, tab.path);
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));
log("error", e instanceof Error ? e.message : String(e), undefined, tab.path);
notifications().notify({
level: "error",
title: "Changes were not submitted",
@@ -815,9 +821,10 @@ function PinButton({ tab }: { tab: ResultTab }) {
}
/** The most recently started console request, while it runs. */
function useLatestExecution(): [string, ConsoleExecution] | undefined {
function useLatestExecution(path?: string): [string, ConsoleExecution] | undefined {
return useDatabase(
useShallow((s) => {
if (path !== undefined) return s.executions[path] ? [path, s.executions[path]] : undefined;
let latest: [string, ConsoleExecution] | undefined;
for (const entry of Object.entries(s.executions))
if (!latest || entry[1].startedAt > latest[1].startedAt) latest = entry;
@@ -854,11 +861,15 @@ function ExecutingBar({ path, execution }: { path: string; execution: ConsoleExe
}
export function ResultsView() {
const results = useDatabase((s) => s.results);
const execution = useLatestExecution();
const active = useDatabase((s) => s.activeResult);
return <ResultsContent />;
}
export function ResultsContent({ path, clientSelector }: { path?: string; clientSelector?: ReactNode }) {
const results = useDatabase(useShallow((s) => resultsFor(s, path)));
const execution = useLatestExecution(path);
const active = useDatabase((s) => activeResultFor(s, path));
const hasOutput = useDatabase((s) => s.output.length > 0);
const root = useRef<HTMLDivElement>(null);
const tabPrefix = path === undefined ? "db-results" : "db-output-results";
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 = () => {
@@ -867,24 +878,29 @@ export function ResultsView() {
return !!target && document.activeElement === target;
};
useEffect(() => {
const syncFocus = () => setContext("dbResultsFocus", !!root.current?.contains(document.activeElement));
const syncFocus = () => {
const scope = document.activeElement?.closest<HTMLElement>("[data-database-results]");
setContext("dbResultsFocus", !!scope);
setContext("dbResultsPath", scope?.dataset.databaseResultsPath);
};
document.addEventListener("focusin", syncFocus);
syncFocus();
return () => {
document.removeEventListener("focusin", syncFocus);
setContext("dbResultsFocus", false);
syncFocus();
};
}, []);
}, [path]);
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)), {
showContextMenu(e.clientX || e.clientY ? e : { x: rect.left, y: rect.bottom }, resultTabMenu(Number(id), path), {
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)
if (path === undefined && !results.length && !hasOutput && executing)
return <div className={styles.view}>{executing}</div>;
if (path === undefined && !results.length && !hasOutput)
return (
<EmptyState title="No results">
<T>Execute a statement in a query console with ⌘↩.</T>
@@ -893,60 +909,70 @@ export function ResultsView() {
const tab = results.find((r) => r.id === active);
return (
<div
ref={root}
className={styles.view}
data-focus-scope=""
data-database-results=""
data-database-results-path={path}
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;
if (!tab?.id.startsWith(`${tabPrefix}-tab-`)) return;
e.preventDefault();
const rect = tab.getBoundingClientRect();
showContextMenu(
{ x: rect.left, y: rect.bottom },
resultTabMenu(Number(tab.id.slice("db-results-tab-".length))),
resultTabMenu(Number(tab.id.slice(tabPrefix.length + "-tab-".length)), path),
{ 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,
})),
]}
/>
<div className={clientSelector ? styles.outputStrip : undefined}>
{clientSelector}
<Tabs
className={styles.resultTabs}
variant="compact"
aria-label="Results"
activeId={tab ? String(tab.id) : String(OUTPUT_TAB)}
panelIdPrefix={tabPrefix}
focusContent={focusContent}
onSelect={(id) => selectResult(Number(id), path)}
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,
})),
]}
/>
</div>
</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}`}
id={`${tabPrefix}-panel-${tab ? tab.id : OUTPUT_TAB}`}
aria-labelledby={`${tabPrefix}-tab-${tab ? tab.id : OUTPUT_TAB}`}
>
{!tab ? <Output /> : tab.plan ? <PlanResult key={tab.id} tab={tab} /> : <Result key={tab.id} tab={tab} />}
{!tab ? (
<Output path={path} />
) : tab.plan ? (
<PlanResult key={tab.id} tab={tab} />
) : (
<Result key={tab.id} tab={tab} />
)}
</div>
</div>
);
+3
Переглянути файл
@@ -513,17 +513,20 @@ async function executeRange(view: EditorView, path: string, from: number, to: nu
/** Runs the statement at the caret (or the selected ones) of `view`. */
export async function executeInView(view: EditorView, path: string) {
view.focus();
const sel = view.state.selection.main;
await executeRange(view, path, sel.from, sel.to);
}
/** Runs every statement of `view`, in order (stops at the first that fails). */
export async function executeScriptInView(view: EditorView, path: string) {
view.focus();
await executeRange(view, path, 0, view.state.doc.length);
}
/** Explain Plan of the statement at the caret (or the first selected one) of `view`. */
export async function explainInView(view: EditorView, path: string) {
view.focus();
const sel = view.state.selection.main;
await explainConsole(path, view.state.doc.toString(), sel.from, sel.to);
}
+49 -9
Переглянути файл
@@ -27,6 +27,8 @@ import {
registerServiceView,
registerTextEditorWrapper,
registerToolWindow,
SERVICES_WINDOW,
useActiveServiceView,
setFileDecorations,
toolWindowService,
} from "@/workbench/contributions";
@@ -44,7 +46,6 @@ import { nodeSchema, nodeTarget, type DbNode } from "./nodes";
import { registerDatabaseTreeActions } from "./treeActions";
import {
DB_TOOL_WINDOW,
RESULTS_VIEW,
consoleSource,
consoleDecorations,
inEditorResults,
@@ -65,6 +66,51 @@ import {
watchIdleConnections,
} from "./store";
import { DB_OUTPUT_WINDOW, outputDestination, RESULTS_VIEW, revealDatabaseResults } from "./outputDestination";
function registerResultsDestination() {
const registerOutput = () =>
registerToolWindow({
id: DB_OUTPUT_WINDOW,
title: "Database Output",
icon: "db-console",
anchor: "bottom",
stripe: "onUse",
sessionContent: true,
order: 9,
component: lazyComponent(() => import("./DatabaseOutput").then((m) => m.DatabaseOutput)),
});
const disposeServices = registerServiceView({
id: RESULTS_VIEW,
title: "Database",
icon: "database",
order: 20,
onUse: true,
component: lazyComponent(() => import("./ResultsView").then((m) => m.ResultsView)),
});
let destination = outputDestination();
let disposeOutput = destination === "databaseOutput" ? registerOutput() : undefined;
const off = useProject.subscribe((s) => {
const next = outputDestination(s.settings);
if (destination === next) return;
const windows = toolWindowService();
const previous = destination === "databaseOutput" ? DB_OUTPUT_WINDOW : SERVICES_WINDOW;
const reopen =
windows.isVisible(previous) &&
(destination === "databaseOutput" || useActiveServiceView.getState().active === RESULTS_VIEW);
if (reopen) windows.hide(previous);
disposeOutput?.();
destination = next;
disposeOutput = destination === "databaseOutput" ? registerOutput() : undefined;
if (reopen) revealDatabaseResults();
});
return () => {
off();
disposeOutput?.();
disposeServices();
};
}
/**
* The schema a console opened for `id` starts in: the invoking node's, else the selected tree
* node's while it is on the same connection target (#6329).
@@ -199,14 +245,7 @@ export function activate(): () => void {
void loadSourceFolders();
}),
registerDatabaseWindow(),
registerServiceView({
id: RESULTS_VIEW,
title: "Database",
icon: "database",
order: 20,
onUse: true,
component: lazyComponent(() => import("./ResultsView").then((m) => m.ResultsView)),
}),
registerResultsDestination(),
registerEditorKind({
kind: TABLE_KIND,
component: lazyComponent(() => import("./TableEditor").then((m) => m.TableEditor)),
@@ -268,6 +307,7 @@ export function activate(): () => void {
inline: [],
output: [],
activeResult: null,
activeClientResults: {},
selectedSource: null,
selectedNode: null,
selectedNodes: [],
+29
Переглянути файл
@@ -0,0 +1,29 @@
import { useProject } from "@/platform/project";
import { showServiceView, toolWindowService } from "@/workbench/contributions";
export const DB_OUTPUT_WINDOW = "databaseOutput";
export const RESULTS_VIEW = "dbResults";
export function outputDestination(settings: unknown = useProject.getState().settings): "databaseOutput" | "services" {
return (settings as { database?: { outputDestination?: unknown } } | null)?.database?.outputDestination === "services"
? "services"
: "databaseOutput";
}
const outputRevealListeners = new Set<(path: string) => void>();
export function onOutputReveal(listener: (path: string) => void) {
outputRevealListeners.add(listener);
return () => {
outputRevealListeners.delete(listener);
};
}
export function revealDatabaseResults(path?: string) {
if (outputDestination() === "services") {
showServiceView(RESULTS_VIEW, false);
} else {
if (path !== undefined) for (const listener of outputRevealListeners) listener(path);
toolWindowService().show(DB_OUTPUT_WINDOW, false);
}
}
+57 -30
Переглянути файл
@@ -1,11 +1,35 @@
import { registerActions, type ActionContext } from "@/platform/actions";
import { promptInput } from "@/workbench/inputDialogs";
import type { MenuItem } from "@/ui";
import { OUTPUT_TAB, closeResult, pinResult, useDatabase } from "./store";
import { OUTPUT_TAB, activeResultFor, closeResult, pinResult, resultsFor, selectResult, useDatabase } from "./store";
function target({ arg, ctx }: ActionContext): number | null {
const id = typeof arg === "number" ? arg : ctx.dbResultsFocus ? useDatabase.getState().activeResult : null;
return id === OUTPUT_TAB || useDatabase.getState().results.some((r) => r.id === id) ? id : null;
interface ResultActionArg {
id: number;
path: string;
}
function pathFor({ arg, ctx }: ActionContext): string | undefined {
if (typeof arg === "number") return undefined;
return arg && typeof arg === "object" && "path" in arg
? (arg as ResultActionArg).path
: typeof ctx.dbResultsPath === "string"
? ctx.dbResultsPath
: undefined;
}
function target(c: ActionContext): number | null {
const { arg, ctx } = c;
const s = useDatabase.getState();
const path = pathFor(c);
const id =
typeof arg === "number"
? arg
: arg && typeof arg === "object" && "id" in arg
? (arg as ResultActionArg).id
: ctx.dbResultsFocus
? activeResultFor(s, path)
: null;
return id === OUTPUT_TAB || resultsFor(s, path).some((r) => r.id === id) ? id : null;
}
function closable(c: ActionContext): boolean {
@@ -13,27 +37,28 @@ function closable(c: ActionContext): boolean {
return id !== null && id !== OUTPUT_TAB;
}
function closeOthers(id: number) {
for (const tab of useDatabase.getState().results) if (tab.id !== id) closeResult(tab.id);
function closeOthers(id: number, path?: string) {
for (const tab of resultsFor(useDatabase.getState(), path)) if (tab.id !== id) closeResult(tab.id);
}
function pinned(id: number | null): boolean {
return !!useDatabase.getState().results.find((r) => r.id === id)?.pinned;
}
function cycle(direction: 1 | -1, focus: boolean) {
const { results, activeResult } = useDatabase.getState();
const ids = [OUTPUT_TAB, ...results.map((r) => r.id)];
const index = ids.indexOf(activeResult ?? OUTPUT_TAB);
function cycle(direction: 1 | -1, focus: boolean, path?: string) {
const state = useDatabase.getState();
const ids = [OUTPUT_TAB, ...resultsFor(state, path).map((r) => r.id)];
const index = ids.indexOf(activeResultFor(state, path));
if (index < 0) return;
const next = ids[(index + direction + ids.length) % ids.length]!;
if (focus) {
const button = document.getElementById(`db-results-tab-${next}`);
const prefix = path === undefined ? "db-results" : "db-output-results";
const button = document.getElementById(`${prefix}-tab-${next}`);
button?.focus();
// An inline editor can hand focus back to its grid when it blurs.
if (document.activeElement !== button) button?.focus();
}
useDatabase.setState({ activeResult: next });
selectResult(next, path);
}
export function registerResultTabActions(): () => void {
@@ -52,16 +77,17 @@ export function registerResultTabActions(): () => void {
title: "Close Others",
category: "Database",
keyWhen: "dbResultsFocus && !popupOpen",
enabled: (c) => target(c) !== null && useDatabase.getState().results.some((r) => r.id !== target(c)),
run: (c) => closeOthers(target(c)!),
enabled: (c) =>
target(c) !== null && resultsFor(useDatabase.getState(), pathFor(c)).some((r) => r.id !== target(c)),
run: (c) => closeOthers(target(c)!, pathFor(c)),
},
{
id: "db.closeAllResultTabs",
title: "Close All",
category: "Database",
keyWhen: "dbResultsFocus && !popupOpen",
enabled: (c) => target(c) !== null && useDatabase.getState().results.length > 0,
run: () => closeOthers(OUTPUT_TAB),
enabled: (c) => target(c) !== null && resultsFor(useDatabase.getState(), pathFor(c)).length > 0,
run: (c) => closeOthers(OUTPUT_TAB, pathFor(c)),
},
{
id: "db.closeAllButPinnedResultTabs",
@@ -69,11 +95,11 @@ export function registerResultTabActions(): () => void {
category: "Database",
keyWhen: "dbResultsFocus && !popupOpen",
enabled: (c) => {
const { results } = useDatabase.getState();
const results = resultsFor(useDatabase.getState(), pathFor(c));
return target(c) !== null && results.some((r) => r.pinned) && results.some((r) => !r.pinned);
},
run: () => {
for (const tab of useDatabase.getState().results) if (!tab.pinned) closeResult(tab.id);
run: (c) => {
for (const tab of resultsFor(useDatabase.getState(), pathFor(c))) if (!tab.pinned) closeResult(tab.id);
},
},
{
@@ -109,23 +135,24 @@ export function registerResultTabActions(): () => void {
title: direction === 1 ? "Select Next Tab" : "Select Previous Tab",
category: "Database",
keyWhen: "dbResultsFocus && !popupOpen",
enabled: (c: ActionContext) => target(c) !== null && useDatabase.getState().results.length > 0,
run: ({ ctx }: ActionContext) => cycle(direction, !!ctx.dbResultsFocus),
enabled: (c: ActionContext) => target(c) !== null && resultsFor(useDatabase.getState(), pathFor(c)).length > 0,
run: (c: ActionContext) => cycle(direction, !!c.ctx.dbResultsFocus, pathFor(c)),
})),
]);
}
export function resultTabMenu(id: number): MenuItem[] {
export function resultTabMenu(id: number, path?: string): MenuItem[] {
const arg = path === undefined ? id : { id, path };
return [
{ kind: "action", action: "db.closeResultTab", arg: id },
{ kind: "action", action: "db.closeOtherResultTabs", arg: id },
{ kind: "action", action: "db.closeAllResultTabs", arg: id },
{ kind: "action", action: "db.closeAllButPinnedResultTabs", arg: id },
{ kind: "action", action: "db.closeResultTab", arg },
{ kind: "action", action: "db.closeOtherResultTabs", arg },
{ kind: "action", action: "db.closeAllResultTabs", arg },
{ kind: "action", action: "db.closeAllButPinnedResultTabs", arg },
{ kind: "separator" },
{ kind: "action", action: "db.pinResultTab", arg: id, label: pinned(id) ? "Unpin Tab" : "Pin Tab" },
{ kind: "action", action: "db.renameResultTab", arg: id },
{ kind: "action", action: "db.pinResultTab", arg, label: pinned(id) ? "Unpin Tab" : "Pin Tab" },
{ kind: "action", action: "db.renameResultTab", arg },
{ kind: "separator" },
{ kind: "action", action: "db.nextResultTab", arg: id },
{ kind: "action", action: "db.previousResultTab", arg: id },
{ kind: "action", action: "db.nextResultTab", arg },
{ kind: "action", action: "db.previousResultTab", arg },
];
}
+17 -1
Переглянути файл
@@ -14,7 +14,7 @@ import { disableRemote, enableRemote } from "@/platform/remote";
import { useProject } from "@/platform/project";
import { installCellActions } from "./cellActions";
import { getContext } from "@/platform/context";
import { ResultsView } from "./ResultsView";
import { ResultsContent, ResultsView } from "./ResultsView";
import { streamExecution } from "./executeStream.fixture";
import {
cancelConsole,
@@ -473,6 +473,22 @@ describe("editable result grid", () => {
expect(backend.applyEdits).not.toHaveBeenCalled();
});
it("keeps pinned pending edits when moving the same result between output windows", async () => {
const result = show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
const view = render(<ResultsContent path={result.path} />);
fireEvent.click(await screen.findByRole("button", { name: "Pin Tab" }));
fireEvent.doubleClick(screen.getByRole("gridcell", { name: "Ann" }));
const cell = screen.getByRole("textbox", { name: "Edit name" });
fireEvent.change(cell, { target: { value: "Bob" } });
fireEvent.keyDown(cell, { key: "Enter" });
view.rerender(<ResultsView />);
expect(screen.getByRole("gridcell", { name: "Bob" })).toBeVisible();
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
expect(screen.getByRole("button", { name: "Pin Tab" })).toHaveAttribute("aria-pressed", "true");
expect(backend.applyEdits).not.toHaveBeenCalled();
});
it("keeps unsubmitted edits while another result tab is shown", async () => {
const first = show("SELECT * FROM users WHERE id < 10", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
const second: ResultTab = {
+130 -46
Переглянути файл
@@ -39,7 +39,6 @@ import {
editorService,
maybeEditorService,
notifications,
showServiceView,
toolWindowService,
type FileDecoration,
} from "@/workbench/contributions";
@@ -74,9 +73,10 @@ import type { TableSnapshot } from "./schemaCompare";
import { resolutionScopeOf, resolutionScopesOf, type SqlResolutionScope } from "./resolutionScopes";
import { databaseRequest, invalidateDatabaseRequests, projectRequest } from "./requests";
import { tx } from "@/platform/i18n";
import { revealDatabaseResults } from "./outputDestination";
export { RESULTS_VIEW } from "./outputDestination";
export const DB_TOOL_WINDOW = "database";
export const RESULTS_VIEW = "dbResults";
const BINDINGS_KEY = "openidea.database.consoles";
const CONSOLE_SCHEMAS_KEY = "openidea.database.consoleSchemas";
const VIEW_OPTIONS_KEY = "openidea.database.viewOptions";
@@ -131,6 +131,8 @@ export interface OutputLine {
text: string;
/** Prompt before a statement: the schema it ran in (`main>`). */
prompt?: string;
/** SQL console or file that emitted the line. */
path?: string;
}
/** `activeResult` value of the Output tab. */
@@ -238,6 +240,7 @@ interface DatabaseState {
inline: ResultTab[];
/** Result tab id, or `OUTPUT_TAB`. */
activeResult: number | null;
activeClientResults: Record<string, number>;
output: OutputLine[];
/** Console path → running request. */
running: Record<string, RequestId>;
@@ -332,6 +335,7 @@ export const useDatabase = create<DatabaseState>(() => ({
results: [],
inline: [],
activeResult: null,
activeClientResults: {},
output: [],
running: {},
executions: {},
@@ -1289,6 +1293,7 @@ interface ConsoleScope {
const consoleScopes = new Map<string, ConsoleScope>();
const closingConsoles = new Map<string, Promise<unknown>>();
const pendingExplains = new Map<string, RequestId>();
const stopResultDelivery = new Map<RequestId, () => void>();
const incompleteResultDelivery = Symbol("incomplete SQL result delivery");
const streamingResultTabs = new Set<number>();
@@ -1327,6 +1332,7 @@ useProject.subscribe((state, previous) => {
for (const scope of consoleScopes.values()) scope.retired = true;
consoleScopes.clear();
closingConsoles.clear();
pendingExplains.clear();
lastUsed.clear();
if (useDatabase.getState().pausedConsoleMetadata.size) useDatabase.setState({ pausedConsoleMetadata: new Set() });
});
@@ -1475,17 +1481,17 @@ let nextTab = 1;
let nextRun = 1;
let nextLine = 1;
function outputLine(kind: OutputLine["kind"], text: string, prompt?: string): OutputLine {
return { id: nextLine++, time: Date.now(), kind, text, prompt };
function outputLine(kind: OutputLine["kind"], text: string, prompt?: string, path?: string): OutputLine {
return { id: nextLine++, time: Date.now(), kind, text, prompt, path };
}
export function log(kind: OutputLine["kind"], text: string, prompt?: string) {
const line = outputLine(kind, text, prompt);
export function log(kind: OutputLine["kind"], text: string, prompt?: string, path?: string) {
const line = outputLine(kind, text, prompt, path);
useDatabase.setState((s) => ({ output: [...s.output, line].slice(-MAX_OUTPUT) }));
}
export function clearOutput() {
useDatabase.setState({ output: [] });
export function clearOutput(path?: string) {
useDatabase.setState((s) => ({ output: path === undefined ? [] : s.output.filter((line) => line.path !== path) }));
}
function elapsed(ms: number): string {
@@ -1523,13 +1529,13 @@ function outcomeUpdates(
path?: string,
): Pick<DatabaseState, "output" | "pendingTx" | "consolePendingTx"> {
const prompt = `${schema || promptOf(id)}>`;
const lines = logConnected ? [outputLine("info", "Connected")] : [];
const lines = logConnected ? [outputLine("info", "Connected", undefined, path)] : [];
for (const outcome of outcomes) {
lines.push(outputLine("statement", outcome.statement.text, prompt));
lines.push(outputLine("statement", outcome.statement.text, prompt, path));
lines.push(
outcome.error
? outputLine("error", `[${targetLabel(id)}] ${outcome.error}`)
: outputLine("result", outcomeSummary(outcome)),
? outputLine("error", `[${targetLabel(id)}] ${outcome.error}`, undefined, path)
: outputLine("result", outcomeSummary(outcome), undefined, path),
);
}
const pending =
@@ -1551,7 +1557,7 @@ function outcomeUpdates(
* each statement in it, so unqualified names resolve there.
*/
/** Shows `id` disconnected when the backend closed its connection (it reconnects on next use). */
async function syncDropped(id: string) {
async function syncDropped(id: string, path?: string) {
const current = databaseRequest(id);
const server = await call(commands.dbConnected()).catch(() => null);
if (!current() || !server || server.includes(id) || !useDatabase.getState().connected.has(id)) return;
@@ -1560,7 +1566,7 @@ async function syncDropped(id: string) {
connected.delete(id);
return { connected };
});
log("info", `${targetLabel(id)}: the connection was lost; the next statement reconnects`);
log("info", `${targetLabel(id)}: the connection was lost; the next statement reconnects`, undefined, path);
}
function consoleScopeKey(id: string, path: string): string {
@@ -1781,7 +1787,7 @@ async function run(
});
if (!current()) return outcomes;
// A failed statement can have found the session dead; the backend then dropped it.
if (outcomes.some((o) => o.error)) void syncDropped(id);
if (outcomes.some((o) => o.error)) void syncDropped(id, path);
// Consoles publish the same outcome updates alongside their progress and grids.
if (progress) return outcomes;
useDatabase.setState((s) => outcomeUpdates(s, id, schema, outcomes, !wasConnected, path));
@@ -1976,16 +1982,19 @@ export async function executeConsole(
const request = nextRequestId();
const ownsRun = () => current() && useDatabase.getState().running[path] === request;
preparingConsoles.set(path, request);
const earlierExplain = pendingExplains.get(path);
const resultIds = new Set<number>();
let finished = false;
let selectOutput = false;
let schemaChanged = false;
let statementCancelled = false;
let deliveryIncomplete = false;
const inline = inEditorResults();
try {
const statements = await consoleStatements(id, text, from, to, confirmUnsafe);
if (!current() || preparingConsoles.get(path) !== request || !statements.length) return [];
preparingConsoles.delete(path);
if (pendingExplains.get(path) === earlierExplain) pendingExplains.delete(path);
const prev = useDatabase.getState().running[path];
if (prev) cancelExecution(prev);
const execution = { startedAt: Date.now(), statements: statements.length, active: null };
@@ -1994,8 +2003,7 @@ export async function executeConsole(
executions: { ...s.executions, [path]: execution },
}));
onStart?.(statements);
const inline = inEditorResults();
if (!inline) showServiceView(RESULTS_VIEW, false);
if (!inline) revealDatabaseResults(path);
const pageSize = useDatabase.getState().maxRows;
const schema = consoleSchema(path) || (await loadCompletion(id))?.defaultSchema || "";
if (!ownsRun() || (wasOpen && !editor?.openPaths?.()?.includes(path))) return [];
@@ -2035,7 +2043,12 @@ export async function executeConsole(
const latest = tabs.at(-1);
if (!latest) return state;
if (inline) return { ...state, inline: [...s.inline, ...tabs.map((tab) => ({ ...tab, inline: true }))] };
return { ...state, results: capResults([...s.results, ...tabs], resultIds), activeResult: latest.id };
return {
...state,
results: capResults([...s.results, ...tabs], resultIds),
activeResult: latest.id,
activeClientResults: { ...s.activeClientResults, [path]: latest.id },
};
});
if (completed.length) logConnected = false;
};
@@ -2064,7 +2077,7 @@ export async function executeConsole(
if (!ownsRun()) return [];
if (deliveryIncomplete) {
const summary = tx("SQL result delivery was incomplete. The final execution status is unknown.");
log("info", summary);
log("info", summary, undefined, path);
notifications().notify({ level: "warning", title: summary, key: "db-execute" });
if (consoleUsesManualCommit(useDatabase.getState(), id, path)) setPending(id, true, path);
}
@@ -2074,13 +2087,14 @@ export async function executeConsole(
} catch (e) {
if (!current() || (!ownsRun() && preparingConsoles.get(path) !== request)) return [];
if (!isCancelled(e)) {
log("error", message(e));
if (!inline) showOutputFor(path);
log("error", message(e), undefined, path);
notifications().notify({ level: "error", title: "Cannot execute", body: message(e), key: "db-execute" });
} else {
log("info", "Cancelled");
log("info", "Cancelled", undefined, path);
// Interrupting a running statement discards its held transaction. Between statements it stays open.
if (statementCancelled && consoleHasPending(useDatabase.getState(), id, path)) {
log("info", "Transaction rolled back");
log("info", "Transaction rolled back", undefined, path);
setPending(id, false, path);
}
}
@@ -2107,7 +2121,15 @@ export async function executeConsole(
)
: capResults(s.results, resultIds);
}
return { running, executions, results, activeResult: selectOutput ? OUTPUT_TAB : s.activeResult };
return {
running,
executions,
results,
...(selectOutput && {
activeResult: OUTPUT_TAB,
activeClientResults: { ...s.activeClientResults, [path]: OUTPUT_TAB },
}),
};
});
if (refreshMetadata) void refresh(id);
}
@@ -2167,10 +2189,17 @@ async function consoleStatements(
const PLAN_TITLE = "Query Plan";
/** Shows `plan` of `statement` in the window's Query Plan tab (one per window, like IDEA's). */
function showPlan(path: string, id: string, statement: SqlStatement, schema: string | undefined, plan: DbPlanNode[]) {
/** Publishes the plan, selecting its tab only if Explain still owns the selection. */
function showPlan(
path: string,
id: string,
statement: SqlStatement,
schema: string | undefined,
plan: DbPlanNode[],
select: boolean,
) {
useDatabase.setState((s) => {
const old = s.results.find((r) => r.plan && !r.pinned);
const old = select ? s.results.find((r) => r.path === path && r.plan && !r.pinned) : undefined;
const tab: ResultTab = {
id: old?.id ?? nextTab++,
title: old?.title ?? PLAN_TITLE,
@@ -2180,12 +2209,15 @@ function showPlan(path: string, id: string, statement: SqlStatement, schema: str
outcome: { statement, result: null, error: null },
plan,
};
const results = old
? s.results.map((r) => (r === old ? tab : r))
: capResults([...s.results, tab], new Set([tab.id]));
return { results, activeResult: tab.id };
const active = select ? tab.id : activeResultFor(s, path);
// Adding a late plan must not evict any of the selected tabs.
const keep = select
? new Set([tab.id])
: new Set([tab.id, active, s.activeResult ?? OUTPUT_TAB, ...Object.values(s.activeClientResults)]);
const results = old ? s.results.map((r) => (r === old ? tab : r)) : capResults([...s.results, tab], keep);
const activeClientResults = { ...s.activeClientResults, [path]: active };
return select ? { results, activeResult: tab.id, activeClientResults } : { results, activeClientResults };
});
showServiceView(RESULTS_VIEW, false);
}
async function explain(
@@ -2193,12 +2225,16 @@ async function explain(
statement: SqlStatement,
schema: string | undefined,
path: string,
request = nextRequestId(),
): Promise<DbPlanNode[]> {
const current = databaseRequest(id);
const plan = await withConsoleConnection(id, path, (console, manual) =>
call(commands.dbExplain(nextRequestId(), id, statement.text, schema || null, console, manual)),
call(commands.dbExplain(request, id, statement.text, schema || null, console, manual)),
);
log("statement", `explain ${statement.text}`, `${schema || promptOf(id)}>`);
log("result", `${plan.length} plan node${plan.length === 1 ? "" : "s"}`);
if (current()) {
log("statement", `explain ${statement.text}`, `${schema || promptOf(id)}>`, path);
log("result", `${plan.length} plan node${plan.length === 1 ? "" : "s"}`, undefined, path);
}
return plan;
}
@@ -2206,20 +2242,30 @@ async function explain(
export async function explainConsole(path: string, text: string, from: number, to: number): Promise<void> {
const id = consoleSource(path);
if (!id || !supportsExplain(sourceById(id))) return;
const current = databaseRequest(id);
const request = nextRequestId();
pendingExplains.set(path, request);
const ownsSelection = () => pendingExplains.get(path) === request;
try {
const [statement] = await consoleStatements(id, text, from, to);
if (!statement) return;
if (!current() || !statement) return;
if (ownsSelection()) revealDatabaseResults(path);
const schema = consoleSchema(path);
showPlan(path, id, statement, schema, await explain(id, statement, schema, path));
const plan = await explain(id, statement, schema, path, request);
if (current()) showPlan(path, id, statement, schema, plan, ownsSelection());
} catch (e) {
if (isCancelled(e)) return;
log("error", `[${targetLabel(id)}] ${message(e)}`);
if (!current() || isCancelled(e)) return;
log("error", `[${targetLabel(id)}] ${message(e)}`, undefined, path);
if (!ownsSelection()) return;
showOutputFor(path);
notifications().notify({
level: "error",
title: "Cannot explain the statement",
body: message(e),
key: "db-explain",
});
} finally {
if (ownsSelection()) pendingExplains.delete(path);
}
}
@@ -2262,7 +2308,7 @@ export async function rerunResult(tabId: number): Promise<void> {
});
} catch (e) {
patchResult(tabId, { busy: false });
if (!isCancelled(e)) log("error", `[${targetLabel(tab.sourceId)}] ${message(e)}`);
if (!isCancelled(e)) log("error", `[${targetLabel(tab.sourceId)}] ${message(e)}`, undefined, tab.path);
}
return;
}
@@ -2353,11 +2399,10 @@ export async function loadResultPage(tabId: number, page: number, pageSize: numb
});
} else patchResult(tabId, { busy: false });
// A run of its console may have replaced the tab meanwhile.
if (outcome?.error && useDatabase.getState().results.some((r) => r.id === tabId))
useDatabase.setState({ activeResult: OUTPUT_TAB });
if (outcome?.error && useDatabase.getState().results.some((r) => r.id === tabId)) showOutputFor(tab.path);
} catch (e) {
patchResult(tabId, { busy: false });
if (!isCancelled(e)) log("error", message(e));
if (!isCancelled(e)) log("error", message(e), undefined, tab.path);
}
}
@@ -2395,7 +2440,7 @@ export async function countResult(tabId: number): Promise<number | null> {
return known;
} catch (e) {
patchResult(tabId, { busy: false });
if (!isCancelled(e)) log("error", message(e));
if (!isCancelled(e)) log("error", message(e), undefined, tab.path);
return null;
}
}
@@ -2441,12 +2486,12 @@ export async function finishTransaction(id: string, commit: boolean, path?: stri
: commands.dbFinishTransaction(id, commit),
);
if (!current()) return false;
log("statement", commit ? "commit" : "rollback", `${promptOf(id)}>`);
log("result", commit ? "Transaction committed" : "Transaction rolled back");
log("statement", commit ? "commit" : "rollback", `${promptOf(id)}>`, path);
log("result", commit ? "Transaction committed" : "Transaction rolled back", undefined, path);
setPending(id, false, path);
return true;
} catch (e) {
log("error", `[${targetLabel(id)}] ${message(e)}`);
log("error", `[${targetLabel(id)}] ${message(e)}`, undefined, path);
notifications().notify({ level: "error", title: commit ? "Cannot commit" : "Cannot roll back", body: message(e) });
return false;
}
@@ -2517,14 +2562,53 @@ function cancelExecution(request: RequestId) {
void commands.cancelRequest(request);
}
export function resultsFor(s: Pick<DatabaseState, "results">, path?: string) {
return path === undefined ? s.results : s.results.filter((tab) => tab.path === path);
}
export function activeResultFor(
s: Pick<DatabaseState, "activeResult" | "activeClientResults" | "results">,
path?: string,
) {
const selected = path === undefined ? s.activeResult : s.activeClientResults[path];
if (
selected === OUTPUT_TAB ||
s.results.some((tab) => tab.id === selected && (path === undefined || tab.path === path))
)
return selected ?? OUTPUT_TAB;
return path === undefined ? OUTPUT_TAB : (resultsFor(s, path).at(-1)?.id ?? OUTPUT_TAB);
}
function showOutputFor(path: string) {
useDatabase.setState((s) => ({
activeResult: OUTPUT_TAB,
activeClientResults: { ...s.activeClientResults, [path]: OUTPUT_TAB },
}));
}
export function selectResult(id: number, path?: string) {
useDatabase.setState((s) =>
path === undefined ? { activeResult: id } : { activeClientResults: { ...s.activeClientResults, [path]: id } },
);
}
export function closeResult(id: number) {
useDatabase.setState((s) => {
const index = s.results.findIndex((r) => r.id === id);
if (index < 0) return s;
const path = s.results[index]!.path;
const results = s.results.filter((r) => r.id !== id);
const sameClient = resultsFor(s, path);
const clientIndex = sameClient.findIndex((r) => r.id === id);
return {
results,
activeResult: s.activeResult === id ? ((results[index - 1] ?? results[index])?.id ?? OUTPUT_TAB) : s.activeResult,
...(s.activeClientResults[path] === id && {
activeClientResults: {
...s.activeClientResults,
[path]: (sameClient[clientIndex - 1] ?? sameClient[clientIndex + 1])?.id ?? OUTPUT_TAB,
},
}),
};
});
}
+8 -2
Переглянути файл
@@ -68,7 +68,11 @@ export interface ValidSettings extends WorkflowSettings {
scopes: NamedScope[];
fileColors: FileColorSettings;
/** Database › Query Execution. */
database: { inEditorResults: boolean; resolutionScopes: Array<{ path: string; dataSource: string; schema: string }> };
database: {
inEditorResults: boolean;
outputDestination: "databaseOutput" | "services";
resolutionScopes: Array<{ path: string; dataSource: string; schema: string }>;
};
general: {
reopenLastProject: boolean;
confirmExit: boolean;
@@ -185,7 +189,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
plugins: {},
scopes: [],
fileColors: DEFAULT_FILE_COLORS,
database: { inEditorResults: false, resolutionScopes: [] },
database: { inEditorResults: false, outputDestination: "databaseOutput", resolutionScopes: [] },
general: {
reopenLastProject: true,
confirmExit: true,
@@ -374,6 +378,8 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
fileColors: validateFileColors(root.fileColors),
database: {
inEditorResults: bool(obj(root.database).inEditorResults, d.database.inEditorResults),
outputDestination:
obj(root.database).outputDestination === "services" ? "services" : d.database.outputDestination,
resolutionScopes: (Array.isArray(obj(root.database).resolutionScopes)
? (obj(root.database).resolutionScopes as unknown[])
: []
+22
Переглянути файл
@@ -757,6 +757,28 @@ function ExternalToolsEditor() {
}
export const TOOLS_PAGES: PageSpec[] = [
{
id: "tools.database",
title: "Database",
group: TOOLS_GROUP,
order: 603,
sections: [
{
title: "Query Output",
options: [
{
kind: "select",
key: "database.outputDestination",
label: "Show query results in",
options: [
{ value: "databaseOutput", label: "Database Output" },
{ value: "services", label: "Services" },
],
},
],
},
],
},
{
id: "tools.terminal",
title: "Terminal",
+6
Переглянути файл
@@ -1,4 +1,5 @@
{
"No SQL client": "No SQL client",
"No images to compare": "No images to compare",
"Image diff": "Image diff",
"Highlight changed pixels": "Highlight changed pixels",
@@ -16,10 +17,13 @@
"Appended to the launch command. Quote values containing spaces.": "Appended to the launch command. Quote values containing spaces.",
"Reset additional arguments": "Reset additional arguments",
"Close the quoted argument before applying.": "Close the quoted argument before applying.",
"SQL client": "SQL client",
"Open Client in Editor": "Open Client in Editor",
"Short Go error guards and case clauses": "Short Go error guards and case clauses",
"Create function '{name}'": "Create function '{name}'",
"Create class '{name}'": "Create class '{name}'",
"Create method '{name}' in '{owner}'": "Create method '{name}' in '{owner}'",
"Database Output": "Database Output",
"Docstring stubs (Enter after \"\"\") are written in this markup format, and docstring tags and keywords are highlighted according to it (Color Scheme › Python styles their colours).": "Docstring stubs (Enter after \"\"\") are written in this markup format, and docstring tags and keywords are highlighted according to it (Color Scheme › Python styles their colours).",
"Default dictionary": "Default dictionary",
"The dictionary the editor's Save '…' to dictionary quick fix writes to.": "The dictionary the editor's Save '…' to dictionary quick fix writes to.",
@@ -45,6 +49,7 @@
"Amend commit created": "Amend commit created",
"Could not keep the prepared amend commit": "Could not keep the prepared amend commit",
"The prepared amend commit is no longer available.": "The prepared amend commit is no longer available.",
"Show query results in": "Show query results in",
"Staged changes for the prepared amend commit have changed.": "Staged changes for the prepared amend commit have changed.",
"Choose Commit to Amend": "Choose Commit to Amend",
"Amend Last Commit": "Amend Last Commit",
@@ -1258,6 +1263,7 @@
"Couldn't stop the background task": "Couldn't stop the background task",
"Copy Markdown": "Copy Markdown",
"Couldn't copy the reply": "Couldn't copy the reply",
"Query Output": "Query Output",
"Quote Reply": "Quote Reply",
"Regenerate Response": "Regenerate Response",
"Couldn't regenerate the response": "Couldn't regenerate the response",
+6
Переглянути файл
@@ -1,4 +1,5 @@
{
"No SQL client": "没有 SQL 客户端",
"No images to compare": "没有可比较的图像",
"Image diff": "图像差异",
"Highlight changed pixels": "高亮显示更改的像素",
@@ -13,10 +14,13 @@
"View source diff": "查看源代码差异",
"Image preview": "图像预览",
"No image on this side": "此侧无图像",
"SQL client": "SQL 客户端",
"Open Client in Editor": "在编辑器中打开客户端",
"Short Go error guards and case clauses": "简短的 Go 错误检查和 case 分支",
"Create function '{name}'": "创建函数 '{name}'",
"Create class '{name}'": "创建类 '{name}'",
"Create method '{name}' in '{owner}'": "在 '{owner}' 中创建方法 '{name}'",
"Database Output": "数据库输出",
"Dataclasses, enums, named tuples, typed dicts and models get __init__ on their own": "数据类、枚举、具名元组、TypedDict 和模型会自动获得 __init__",
"Constructor (__init__)…": "构造函数 (__init__)…",
"Property…": "属性 (property)…",
@@ -32,6 +36,7 @@
"Amend commit created": "已创建修订提交",
"Could not keep the prepared amend commit": "无法保留已准备好的修订提交",
"The prepared amend commit is no longer available.": "已准备好的修订提交已失效。",
"Show query results in": "显示查询结果的位置",
"Staged changes for the prepared amend commit have changed.": "此修订提交涉及的暂存改动已发生变化。",
"Choose Commit to Amend": "选择要修订的提交",
"Amend Last Commit": "修订最近一次提交",
@@ -1110,6 +1115,7 @@
"Fill Paragraph": "填充段落",
"Unwrap/Remove…": "解包/移除…",
"Basic": "基本补全",
"Query Output": "查询输出",
"Quick Definition": "快速定义",
"Extract/Introduce": "提取/引入",
"Reformat File…": "重新格式化文件…",