diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index a18dd985f6..b0dcb0eb04 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -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::(saved).unwrap().database, services.database); + } + #[test] fn window_close_settings_default_off_and_round_trip() { for old in [r#"{}"#, r#"{"general":{"confirmExit":false}}"#] { diff --git a/crates/ide-core/src/workflow_settings.rs b/crates/ide-core/src/workflow_settings.rs index 387a339bf9..b26e9fce68 100644 --- a/crates/ide-core/src/workflow_settings.rs +++ b/crates/ide-core/src/workflow_settings.rs @@ -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, } +/// 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")] diff --git a/docs/en/guide/database.mdx b/docs/en/guide/database.mdx index 282719832d..a6119637bc 100644 --- a/docs/en/guide/database.mdx +++ b/docs/en/guide/database.mdx @@ -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. diff --git a/docs/zh/guide/database.mdx b/docs/zh/guide/database.mdx index dd099bb84f..e0409c825f 100644 --- a/docs/zh/guide/database.mdx +++ b/docs/zh/guide/database.mdx @@ -153,7 +153,9 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外 ## 结果与数据编辑 -结果显示在 **服务** 工具窗口的 **数据库** 标签页中:**输出** 标签页记录每条语句,每个结果集一个 **Result N** 标签页(最多 12 个,已固定的标签页除外)。 +查询结果在 **数据库输出** 工具窗口中打开,焦点保留在编辑器。该窗口跟随当前的 SQL 控制台或文件。使用 **SQL 客户端** 选择器查看其他客户端的输出、结果和查询计划。选择器会在有数据源时显示其名称。点击 **在编辑器中打开客户端**,可在编辑器中聚焦所选文件。在当前编辑器运行查询或查看查询计划时,窗口会切回该客户端。 + +**输出** 记录当前客户端的语句和错误。每个结果集对应一个 **Result N** 标签页(最多 12 个,已固定的标签页除外)。要恢复在 **服务** 的 **数据库** 标签页中显示结果,请在 **设置** → **工具** → **数据库** 中更改 **显示查询结果的位置**。切换窗口或客户端会保留查询结果和待提交的表格修改。 再次运行控制台会替换它之前的结果:它未固定的结果标签页会让位给新的运行,新运行每个结果集一个标签页(**Result N**;选中的多条语句都返回行时为 **Result N**、**Result N-2**……)。没有结果集的运行(如 `UPDATE`)会保留之前的结果。其他控制台的结果不受影响。 diff --git a/e2e/databaseOutput.spec.ts b/e2e/databaseOutput.spec.ts new file mode 100644 index 0000000000..6d944ef21b --- /dev/null +++ b/e2e/databaseOutput.spec.ts @@ -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((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); + }); +} diff --git a/e2e/databaseResultTabs.spec.ts b/e2e/databaseResultTabs.spec.ts index 8b7c3cbff6..de0a557149 100644 --- a/e2e/databaseResultTabs.spec.ts +++ b/e2e/databaseResultTabs.spec.ts @@ -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({ diff --git a/src/bindings.ts b/src/bindings.ts index 70d2913035..1928e90abe 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -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. diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css index 21d8099c6b..c2dfd1f9a2 100644 --- a/src/features/database/Database.module.css +++ b/src/features/database/Database.module.css @@ -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; diff --git a/src/features/database/DatabaseOutput.tsx b/src/features/database/DatabaseOutput.tsx new file mode 100644 index 0000000000..92416a5cf0 --- /dev/null +++ b/src/features/database/DatabaseOutput.tsx @@ -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 ( + +