Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(editor): show the summary tab while a write statement runs (#12344)

Xsyl.way1bd656fa1fed
diff --git a/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts b/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts
index fc940fefff..98f0b9060e 100644
--- a/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useSqlExecution.spec.ts
@@ -457,6 +457,43 @@ describe("useSqlExecution", () => {
expect(executeCurrentSql).toHaveBeenCalledWith("select * from users where id = 42", { tabId: "tab-1" });
});
+ it.each([
+ { sql: "UPDATE users SET name = 'Ada' WHERE id = 1", returnsRows: false },
+ { sql: "INSERT INTO users(id) VALUES (1) RETURNING id", returnsRows: true },
+ ])("shows a running write in summary and restores returned rows: $sql", async ({ sql, returnsRows }) => {
+ useSettingsStore().editorSettings.confirmDangerousSqlExecution = false;
+ const activeTab = ref<QueryTab | undefined>({ ...queryTab("app"), sql });
+ const activeConnection = ref<ConnectionConfig | undefined>(connection("postgres"));
+ const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
+ let finishExecution!: () => void;
+ const completion = new Promise<void>((resolve) => {
+ finishExecution = resolve;
+ });
+ const execute = vi.spyOn(useQueryStore(), "executeCurrentSql").mockImplementation(async () => {
+ await completion;
+ activeTab.value!.result = {
+ columns: returnsRows ? ["id"] : [],
+ rows: returnsRows ? [[1]] : [],
+ affected_rows: 1,
+ execution_time_ms: 1,
+ };
+ });
+ vi.spyOn(useHistoryStore(), "add").mockResolvedValue(undefined);
+ const execution = useSqlExecution({
+ activeTab: computed(() => activeTab.value),
+ activeConnection: computed(() => activeConnection.value),
+ executableSql: computed(() => sql),
+ activeOutputView,
+ });
+
+ const pending = execution.tryExecute();
+ await vi.waitFor(() => expect(execute).toHaveBeenCalledOnce());
+ expect(activeOutputView.value).toBe("summary");
+ finishExecution();
+ await pending;
+ expect(activeOutputView.value).toBe(returnsRows ? "result" : "summary");
+ });
+
it("opens the result table for a multi-statement batch by default", async () => {
const sql = "SELECT 1;\nSELECT 2;";
const activeTab = ref<QueryTab | undefined>({ ...queryTab("app"), sql });
diff --git a/apps/desktop/src/composables/useSqlExecution.ts b/apps/desktop/src/composables/useSqlExecution.ts
index f509e5466c..269f091beb 100644
--- a/apps/desktop/src/composables/useSqlExecution.ts
+++ b/apps/desktop/src/composables/useSqlExecution.ts
@@ -14,7 +14,7 @@ import { supportsConnectionLevelSqlExecution } from "@/lib/connection/connection
import { classifySqlActivityKind } from "@/lib/history/historyActivityKind";
import { sqlMetadataRefreshTarget } from "@/lib/sql/sqlMetadataRefresh";
import { invalidateObjectMetadataCache } from "@/lib/metadata/objectMetadataCache";
-import { defaultViewForResult } from "@/lib/query/queryResultDefaultView";
+import { defaultViewForResult, statementRunsWithoutResultGrid } from "@/lib/query/queryResultDefaultView";
import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";
import { classifyRedisCommandSafety } from "@/lib/redis/redisCommandSafety";
import { isRedisCommentLine } from "@/lib/redis/redisCommandTokenizer";
@@ -515,10 +515,14 @@ export function useSqlExecution(deps: {
sqlStatementParameterOptionsForCompatibility(executionDatabaseType, executionDatabaseType === "opengauss" ? connectionStore.databaseCompatibilityMode(tab.connectionId, tab.database) : executionDatabaseType === "kingbase" ? executionConnection?.database_info?.compatibilityMode : undefined),
).length;
const redisConsoleSelected = executionDatabaseType === "redis" && tab.uiState?.redisResultViewMode === "console";
+ // A single write/DDL statement has no result grid to show while it runs, so
+ // it starts on the summary tab where the in-flight status is rendered
+ // instead of leaving an empty data grid up (issue #12283).
+ const autoSummaryWhileRunning = statementCount === 1 && !redisConsoleSelected && executionDatabaseType !== "redis" && statementRunsWithoutResultGrid(sql);
// Output-view switching belongs to the tab the user is looking at — both
// when the query starts and when it finishes.
if (deps.activeTab.value?.id === executionTabId) {
- deps.activeOutputView.value = redisConsoleSelected ? "result" : statementCount > 1 ? settingsStore.editorSettings.multiStatementDefaultView : "result";
+ deps.activeOutputView.value = redisConsoleSelected ? "result" : statementCount > 1 ? settingsStore.editorSettings.multiStatementDefaultView : autoSummaryWhileRunning ? "summary" : "result";
}
updateExecutionTabUiState(tab, { autoSwitchedToMessagesDuringExecution: false });
const connName = executionConnection?.name || "";
@@ -568,6 +572,10 @@ export function useSqlExecution(deps: {
deps.activeOutputView.value = targetView;
}
}
+ } else if (executionTabStillActive && autoSummaryWhileRunning && deps.activeOutputView.value === "summary" && ((currentTab.result?.columns.length ?? 0) > 0 || currentTab.results?.some((result) => result.columns.length > 0))) {
+ // `INSERT ... RETURNING` and siblings do return a grid even though their
+ // leading keyword normally means "no result set"; show it once it lands.
+ deps.activeOutputView.value = "result";
}
updateExecutionTabUiState(currentTab, { autoSwitchedToMessagesDuringExecution: false });
const elapsed = Date.now() - start;
diff --git a/apps/desktop/src/lib/__tests__/query/queryResultMessages.spec.ts b/apps/desktop/src/lib/__tests__/query/queryResultMessages.spec.ts
index 8337f3bb1b..d0bb69cab8 100644
--- a/apps/desktop/src/lib/__tests__/query/queryResultMessages.spec.ts
+++ b/apps/desktop/src/lib/__tests__/query/queryResultMessages.spec.ts
@@ -1,10 +1,39 @@
import { describe, expect, it } from "vitest";
import { queryResultMessages } from "@/lib/query/queryResultMessages";
-import { defaultViewForResult } from "@/lib/query/queryResultDefaultView";
+import { defaultViewForResult, statementRunsWithoutResultGrid } from "@/lib/query/queryResultDefaultView";
import type { QueryResult } from "@/types/database";
const messageResult: QueryResult = { columns: ["Message"], rows: [["before"], [""]], affected_rows: 0, execution_time_ms: 1, server_message: true };
+describe("statementRunsWithoutResultGrid", () => {
+ it("flags write and DDL statements that have no grid to show while running", () => {
+ for (const sql of [
+ "INSERT INTO t VALUES (1)",
+ "insert into t select * from s",
+ "UPDATE t SET a = 1",
+ "DELETE FROM t WHERE id = 1",
+ "MERGE INTO t USING s ON (t.id = s.id) WHEN MATCHED THEN UPDATE SET a = 1",
+ "CREATE TABLE t (id int)",
+ "ALTER TABLE t ADD COLUMN a int",
+ "DROP TABLE t",
+ "TRUNCATE TABLE t",
+ "BEGIN",
+ "COMMIT",
+ "SET autocommit = 1",
+ "USE app",
+ " \n -- leading line comment\n /* block */ UPDATE t SET a = 1;",
+ ]) {
+ expect(statementRunsWithoutResultGrid(sql), sql).toBe(true);
+ }
+ });
+
+ it("keeps statements that can return rows on the data tab", () => {
+ for (const sql of ["SELECT 1", "WITH x AS (SELECT 1) SELECT * FROM x", "SHOW TABLES", "DESCRIBE t", "EXPLAIN SELECT 1", "VALUES (1)", "CALL proc()", "EXEC proc", '{ "find": "users" }', "", " "]) {
+ expect(statementRunsWithoutResultGrid(sql), sql).toBe(false);
+ }
+ });
+});
+
describe("SQL Server result messages", () => {
it("collects tagged messages around data and errors in execution order", () => {
const data: QueryResult = { columns: ["Message"], rows: [["not a notice"]], affected_rows: 0, execution_time_ms: 1 };
diff --git a/apps/desktop/src/lib/query/queryResultDefaultView.ts b/apps/desktop/src/lib/query/queryResultDefaultView.ts
index 0934b5e38a..b4d5bbb138 100644
--- a/apps/desktop/src/lib/query/queryResultDefaultView.ts
+++ b/apps/desktop/src/lib/query/queryResultDefaultView.ts
@@ -12,3 +12,73 @@ export function defaultViewForResult(result: Pick<QueryResult, "columns" | "rows
const messageOnly = result.columns.length === 0 && result.rows.length === 0 && result.affected_rows === 0 && (result.messages?.length ?? 0) > 0;
return messageOnly ? "messages" : "summary";
}
+
+/**
+ * Statements that never render a result grid. While one of them runs the data
+ * tab is an empty placeholder, so a single-statement run starts on the summary
+ * tab where the in-flight status is shown (issue #12283).
+ *
+ * `CALL` / `EXEC` are deliberately absent: on MySQL and SQL Server they can
+ * return rows, so those keep the data tab.
+ */
+const RESULT_GRID_FREE_KEYWORDS = new Set([
+ "insert",
+ "update",
+ "delete",
+ "merge",
+ "upsert",
+ "replace",
+ "truncate",
+ "create",
+ "alter",
+ "drop",
+ "rename",
+ "comment",
+ "grant",
+ "revoke",
+ "commit",
+ "rollback",
+ "begin",
+ "start",
+ "set",
+ "use",
+ "savepoint",
+ "lock",
+ "unlock",
+ "analyze",
+ "vacuum",
+ "reindex",
+ "checkpoint",
+ "flush",
+ "reset",
+ "purge",
+]);
+
+export function statementRunsWithoutResultGrid(sql: string): boolean {
+ const keyword = leadingSqlKeyword(sql);
+ return keyword !== null && RESULT_GRID_FREE_KEYWORDS.has(keyword);
+}
+
+function leadingSqlKeyword(sql: string): string | null {
+ let index = 0;
+ while (index < sql.length) {
+ const character = sql[index];
+ if (character === " " || character === "\t" || character === "\n" || character === "\r" || character === ";") {
+ index += 1;
+ continue;
+ }
+ if (character === "-" && sql[index + 1] === "-") {
+ const lineEnd = sql.indexOf("\n", index + 2);
+ index = lineEnd === -1 ? sql.length : lineEnd + 1;
+ continue;
+ }
+ if (character === "/" && sql[index + 1] === "*") {
+ const commentEnd = sql.indexOf("*/", index + 2);
+ index = commentEnd === -1 ? sql.length : commentEnd + 2;
+ continue;
+ }
+ break;
+ }
+ const match = /^[A-Za-z_]+/.exec(sql.slice(index));
+ return match ? match[0].toLowerCase() : null;
+}