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。

feat(history): record truncate, empty, and drop SQL from table actions

lxk955a9990d5fdb08
diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vue
index 2b78d43f88..13dfae3289 100644
--- a/apps/desktop/src/components/objects/ObjectBrowser.vue
+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue
@@ -124,6 +124,7 @@ import { useExportTracker, type ExportTask } from "@/composables/useExportTracke
import { useSettingsStore } from "@/stores/settingsStore";
import { formatSidebarTableNamesForCopy, type SidebarTableCopyTarget } from "@/lib/sidebar/sidebarTableNameCopy";
import { useQueryStore } from "@/stores/queryStore";
+import { getTableMutationHistoryStoreOrNull, recordTableMutationHistory } from "@/lib/history/tableMutationHistory";
import QueryEditor from "@/components/editor/QueryEditor.vue";
import MySqlEventEditor from "@/components/objects/MySqlEventEditor.vue";
import { sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
@@ -1845,10 +1846,24 @@ async function confirmRename() {
async function confirmDrop() {
if (!dropTarget.value) return;
const row = dropTarget.value;
+ let executedSql = "";
+ const start = Date.now();
+ let successRecorded = false;
try {
const sql = dropPreviewSql.value || (await buildDropSqlForRow(row, { cascade: canDropTargetCascade.value && dropTableCascade.value }));
+ executedSql = sql;
const executed = await executeObjectBrowserSqlWithProductionGuard(sql, () => api.executeQuery(props.connection.id, props.database, sql));
if (!executed) return;
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: props.connection.id,
+ connectionName: props.connection.name,
+ database: props.database,
+ sql,
+ elapsedMs: Date.now() - start,
+ success: true,
+ target: row.name,
+ }).catch((err) => console.warn("[DBX] failed to record drop history", err));
+ successRecorded = true;
const successKey = row.type === "VIEW" ? "contextMenu.dropViewSuccess" : row.type === "PROCEDURE" ? "contextMenu.dropProcedureSuccess" : row.type === "FUNCTION" ? "contextMenu.dropFunctionSuccess" : row.type === "EVENT" ? "contextMenu.dropEventSuccess" : "contextMenu.dropTableSuccess";
toast(t(successKey, { name: row.name }));
const cacheSchema = row.schema || selectedSchema.value || props.database;
@@ -1859,6 +1874,18 @@ async function confirmDrop() {
await reload();
await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, row.schema || selectedSchema.value);
} catch (e: any) {
+ if (executedSql && !successRecorded) {
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: props.connection.id,
+ connectionName: props.connection.name,
+ database: props.database,
+ sql: executedSql,
+ elapsedMs: Date.now() - start,
+ success: false,
+ error: e?.message || String(e),
+ target: row.name,
+ }).catch((err) => console.warn("[DBX] failed to record drop history", err));
+ }
toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
}
dropTarget.value = null;
@@ -2105,8 +2132,12 @@ function requestBatchDropTables() {
async function confirmBatchDropTables() {
if (batchDropExecuting.value) return;
batchDropExecuting.value = true;
+ let batchSql = "";
+ let batchDropRecorded = false;
+ let targets: ObjectBrowserRow[] = [];
+ const start = Date.now();
try {
- const targets = await fetchSortedTableRowsForDrop();
+ targets = await fetchSortedTableRowsForDrop();
if (targets.length === 0) return;
batchDropProgress.value = { completed: 0, total: targets.length };
const useCascade = canBatchDropCascade.value && batchDropCascade.value;
@@ -2116,7 +2147,7 @@ async function confirmBatchDropTables() {
sql: await buildDropTableSql(tableAdminSqlOptions(target, { cascade: useCascade })),
})),
);
- const batchSql = plan.map(({ sql }) => sql).join(";\n");
+ batchSql = plan.map(({ sql }) => sql).join(";\n");
const result = await executeObjectBrowserSqlWithProductionGuard(batchSql, () =>
runBatchTableDrop({
databaseType: effectiveDatabaseType.value,
@@ -2130,6 +2161,18 @@ async function confirmBatchDropTables() {
);
if (!result) return;
+ batchDropRecorded = true;
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: props.connection.id,
+ connectionName: props.connection.name,
+ database: props.database,
+ sql: batchSql,
+ elapsedMs: Date.now() - start,
+ success: !result.failed,
+ error: result.failed ? String(result.failed.message || result.failed) : undefined,
+ target: targets.map((t) => t.name).join(", "),
+ }).catch((err) => console.warn("[DBX] failed to record batch drop history", err));
+
for (const row of result.succeeded) closeDroppedTableObjectTabsForRow(row);
if (result.succeeded.length > 0) {
removePinnedObjectBrowserRows(result.succeeded);
@@ -2140,6 +2183,18 @@ async function confirmBatchDropTables() {
if (result.failed) throw result.failed;
toast(t("objects.batchDropSuccess", { count: result.succeeded.length }));
} catch (e: any) {
+ if (!batchDropRecorded && batchSql) {
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: props.connection.id,
+ connectionName: props.connection.name,
+ database: props.database,
+ sql: batchSql,
+ elapsedMs: Date.now() - start,
+ success: false,
+ error: e?.message || String(e),
+ target: targets.map((t) => t.name).join(", "),
+ }).catch((err) => console.warn("[DBX] failed to record batch drop history", err));
+ }
toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
} finally {
batchDropExecuting.value = false;
@@ -2191,6 +2246,9 @@ async function refreshMutatedTableDataTabsForRows(rows: readonly ObjectBrowserRo
async function confirmBatchTruncateTables() {
const targets = [...selectedTableRows.value];
if (targets.length === 0) return;
+ let batchSql = "";
+ const start = Date.now();
+ let successRecorded = false;
try {
const useCascade = canBatchTruncateCascade.value && batchTruncateCascade.value;
const statements = await Promise.all(
@@ -2199,7 +2257,8 @@ async function confirmBatchTruncateTables() {
sql: await buildTruncateTableSql(tableAdminSqlOptions(row, { cascade: useCascade })),
})),
);
- const executed = await executeObjectBrowserSqlWithProductionGuard(statements.map(({ sql }) => sql).join(";\n"), async () => {
+ batchSql = statements.map(({ sql }) => sql).join(";\n");
+ const executed = await executeObjectBrowserSqlWithProductionGuard(batchSql, async () => {
await runBatchTableTruncate(
statements,
async ({ sql }) => {
@@ -2210,12 +2269,34 @@ async function confirmBatchTruncateTables() {
return true;
});
if (!executed) return;
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: props.connection.id,
+ connectionName: props.connection.name,
+ database: props.database,
+ sql: batchSql,
+ elapsedMs: Date.now() - start,
+ success: true,
+ target: targets.map((t) => t.name).join(", "),
+ }).catch((err) => console.warn("[DBX] failed to record batch truncate history", err));
+ successRecorded = true;
toast(t("objects.batchTruncateSuccess", { count: targets.length }));
clearTableSelection();
showBatchTruncateConfirm.value = false;
await reload();
await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, selectedSchema.value);
} catch (e: any) {
+ if (batchSql && !successRecorded) {
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: props.connection.id,
+ connectionName: props.connection.name,
+ database: props.database,
+ sql: batchSql,
+ elapsedMs: Date.now() - start,
+ success: false,
+ error: e?.message || String(e),
+ target: targets.map((t) => t.name).join(", "),
+ }).catch((err) => console.warn("[DBX] failed to record batch truncate history", err));
+ }
toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
}
}
@@ -2245,6 +2326,7 @@ function requestBatchEmptyTables() {
async function confirmBatchEmptyTables() {
const plan = batchEmptyPlan.value.slice();
if (plan.length === 0) return;
+ const start = Date.now();
const asynchronousMutation = effectiveDatabaseType.value === "clickhouse";
const reviewSql = plan.map(({ sql }) => sql).join(";\n");
const result = await executeObjectBrowserSqlWithProductionGuard(reviewSql, () => {
@@ -2253,6 +2335,16 @@ async function confirmBatchEmptyTables() {
});
});
if (!result) return;
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: props.connection.id,
+ connectionName: props.connection.name,
+ database: props.database,
+ sql: reviewSql,
+ elapsedMs: Date.now() - start,
+ success: result.failed.length === 0,
+ error: result.failed.length > 0 ? result.failed.map((f) => `${f.target.target.name}: ${f.error}`).join("; ") : undefined,
+ target: plan.map((p) => p.target.name).join(", "),
+ }).catch((err) => console.warn("[DBX] failed to record batch empty history", err));
for (const failure of result.failed) {
console.error(`Failed to empty table "${failure.target.target.name}":`, failure.error);
}
@@ -2846,13 +2938,39 @@ function requestTruncateTable(row: ObjectBrowserRow) {
async function confirmTruncateTable() {
const row = truncateTarget.value;
if (!row) return;
+ let executedSql = "";
+ const start = Date.now();
+ let successRecorded = false;
try {
const sql = truncatePreviewSql.value || (await buildTruncateTableSql(tableAdminSqlOptions(row, { cascade: canTruncateTargetCascade.value && truncateTableCascade.value })));
+ executedSql = sql;
const executed = await executeObjectBrowserSqlWithProductionGuard(sql, () => api.executeQuery(props.connection.id, props.database, sql));
if (!executed) return;
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: props.connection.id,
+ connectionName: props.connection.name,
+ database: props.database,
+ sql,
+ elapsedMs: Date.now() - start,
+ success: true,
+ target: row.name,
+ }).catch((err) => console.warn("[DBX] failed to record truncate history", err));
+ successRecorded = true;
toast(t("contextMenu.truncateTableSuccess", { name: row.name }));
await refreshMutatedTableDataTabsForRows([row]);
} catch (e: any) {
+ if (executedSql && !successRecorded) {
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: props.connection.id,
+ connectionName: props.connection.name,
+ database: props.database,
+ sql: executedSql,
+ elapsedMs: Date.now() - start,
+ success: false,
+ error: e?.message || String(e),
+ target: row.name,
+ }).catch((err) => console.warn("[DBX] failed to record truncate history", err));
+ }
toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
}
truncateTarget.value = null;
@@ -2921,13 +3039,39 @@ function requestEmptyTable(row: ObjectBrowserRow) {
async function confirmEmptyTable() {
const row = emptyTarget.value;
if (!row) return;
+ let executedSql = "";
+ const start = Date.now();
+ let successRecorded = false;
try {
const sql = emptyPreviewSql.value || (await buildEmptyTableSql(tableAdminSqlOptions(row)));
+ executedSql = sql;
const executed = await executeObjectBrowserSqlWithProductionGuard(sql, () => api.executeQuery(props.connection.id, props.database, sql));
if (!executed) return;
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: props.connection.id,
+ connectionName: props.connection.name,
+ database: props.database,
+ sql,
+ elapsedMs: Date.now() - start,
+ success: true,
+ target: row.name,
+ }).catch((err) => console.warn("[DBX] failed to record empty history", err));
+ successRecorded = true;
toast(t("contextMenu.emptyTableSuccess", { name: row.name }));
await refreshMutatedTableDataTabsForRows([row]);
} catch (e: any) {
+ if (executedSql && !successRecorded) {
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: props.connection.id,
+ connectionName: props.connection.name,
+ database: props.database,
+ sql: executedSql,
+ elapsedMs: Date.now() - start,
+ success: false,
+ error: e?.message || String(e),
+ target: row.name,
+ }).catch((err) => console.warn("[DBX] failed to record empty history", err));
+ }
toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
}
emptyTarget.value = null;
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index fb9d6a5ae4..54441b3c45 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -70,6 +70,7 @@ import {
} from "@lucide/vue";
import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { CONNECTION_ATTEMPT_CANCELLED_MESSAGE, useConnectionStore } from "@/stores/connectionStore";
+import { getTableMutationHistoryStoreOrNull, recordTableMutationHistory } from "@/lib/history/tableMutationHistory";
import { useQueryStore } from "@/stores/queryStore";
import { useSettingsStore } from "@/stores/settingsStore";
import { useSavedSqlStore } from "@/stores/savedSqlStore";
@@ -682,6 +683,9 @@ const {
executeWithProductionGuard: executeTreeNodeSqlWithProductionGuard,
closeDroppedTableObjectTabsForNode,
refreshMutatedTableDataTabsForNode,
+ historyStore: {
+ add: (entry) => getTableMutationHistoryStoreOrNull()?.add(entry) ?? Promise.resolve(),
+ },
});
const batchDropProgress = ref({ completed: 0, total: 0 });
@@ -3530,6 +3534,7 @@ async function confirmBatchDrop() {
}),
);
const batchSql = plan.map(({ sql }) => sql).join(";\n");
+ const startTime = Date.now();
const result = await executeWithProductionSqlGuard({
connection: connectionStore.getConfig(first.connectionId!),
database: first.database!,
@@ -3548,6 +3553,17 @@ async function confirmBatchDrop() {
});
if (!result) return;
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: first.connectionId!,
+ connectionName: connectionStore.getConfig(first.connectionId!)?.name,
+ database: first.database!,
+ sql: batchSql,
+ elapsedMs: Date.now() - startTime,
+ success: !result.failed,
+ error: result.failed ? String(result.failed.message || result.failed) : undefined,
+ target: targets.map((t) => t.label).join(", "),
+ }).catch((err) => console.warn("[DBX] failed to record batch drop history", err));
+
for (const target of result.succeeded) {
closeDroppedTableObjectTabsForNode(target);
connectionStore.removeTreeNode(target.id);
@@ -3564,7 +3580,22 @@ async function confirmBatchDrop() {
await connectionStore.ensureConnected(target.connectionId);
const sql = await dropSqlForTreeNode(target, { cascade: useCascade });
if (!sql) continue;
- await executeTreeNodeSqlWithProductionGuard(target, sql, { database: target.database, schema: target.schema });
+ const startTime = Date.now();
+ const guardResult = await executeTreeNodeSqlWithProductionGuard(target, sql, { database: target.database, schema: target.schema });
+ if (guardResult === undefined) {
+ // The production guard declined the SQL: it was never sent, so keep the
+ // node, skip the history record, and move on to the next target.
+ continue;
+ }
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: target.connectionId,
+ connectionName: connectionStore.getConfig(target.connectionId)?.name,
+ database: target.database,
+ sql,
+ elapsedMs: Date.now() - startTime,
+ success: true,
+ target: target.label,
+ }).catch((err) => console.warn("[DBX] failed to record drop history", err));
closeDroppedTableObjectTabsForNode(target);
// Remove immediately so a later failure cannot leave dropped objects in the tree.
connectionStore.removeTreeNode(target.id);
@@ -3595,8 +3626,19 @@ async function confirmBatchTruncate() {
await connectionStore.ensureConnected(target.connectionId);
const sql = await truncateSqlForTreeNode(target, { cascade: useCascade });
if (!sql) return false;
+ const startTime = Date.now();
const result = await executeTreeNodeSqlWithProductionGuard(target, sql, { database: target.database, schema: target.schema });
- return result === undefined ? false : undefined;
+ if (result === undefined) return false;
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: target.connectionId,
+ connectionName: connectionStore.getConfig(target.connectionId)?.name,
+ database: target.database,
+ sql,
+ elapsedMs: Date.now() - startTime,
+ success: true,
+ target: target.label,
+ }).catch((err) => console.warn("[DBX] failed to record batch truncate history", err));
+ return undefined;
},
refreshMutatedTableDataTabsForNodes,
);
@@ -3616,7 +3658,22 @@ async function confirmBatchEmpty() {
await connectionStore.ensureConnected(target.connectionId);
const sql = await emptySqlForTreeNode(target);
if (!sql) throw new Error("Empty table SQL is unavailable");
- await executeTreeNodeSqlWithProductionGuard(target, sql, { database: target.database, schema: target.schema });
+ const startTime = Date.now();
+ const guardResult = await executeTreeNodeSqlWithProductionGuard(target, sql, { database: target.database, schema: target.schema });
+ if (guardResult === undefined) {
+ // The production guard declined the SQL: it was never sent, so this must
+ // not be recorded as a success nor counted as an emptied table.
+ throw new Error("Production safety confirmation declined");
+ }
+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
+ connectionId: target.connectionId,
+ connectionName: connectionStore.getConfig(target.connectionId)?.name,
+ database: target.database,
+ sql,
+ elapsedMs: Date.now() - startTime,
+ success: true,
+ target: target.label,
+ }).catch((err) => console.warn("[DBX] failed to record batch empty history", err));
});
for (const failure of result.failed) {
console.error(`Failed to empty table "${failure.target.label}":`, failure.error);
diff --git a/apps/desktop/src/composables/__tests__/useSidebarTableMutationRuntime.saphana.spec.ts b/apps/desktop/src/composables/__tests__/useSidebarTableMutationRuntime.saphana.spec.ts
index be6c5153eb..a00243e63f 100644
--- a/apps/desktop/src/composables/__tests__/useSidebarTableMutationRuntime.saphana.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useSidebarTableMutationRuntime.saphana.spec.ts
@@ -49,7 +49,7 @@ function tableNode(database: string | null | undefined): TreeNode {
} as TreeNode;
}
-function runtime(database: string | null | undefined, config: Pick<ConnectionConfig, "db_type"> & Partial<Pick<ConnectionConfig, "driver_profile">> = { db_type: "saphana" }, databaseType: DatabaseType = "saphana") {
+function runtime(database: string | null | undefined, config: Pick<ConnectionConfig, "db_type"> & Partial<Pick<ConnectionConfig, "driver_profile">> = { db_type: "saphana" }, databaseType: DatabaseType = "saphana", historyStore?: any) {
const node = tableNode(database);
const activeNode = shallowRef(node);
const connectionStore = {
@@ -66,6 +66,7 @@ function runtime(database: string | null | undefined, config: Pick<ConnectionCon
executeWithProductionGuard: mocks.executeWithProductionGuard,
closeDroppedTableObjectTabsForNode: mocks.closeDroppedTableObjectTabsForNode,
refreshMutatedTableDataTabsForNode: mocks.refreshMutatedTableDataTabsForNode,
+ historyStore,
});
return { feature, node };
}
@@ -456,4 +457,55 @@ describe("useSidebarTableMutationRuntime SAP HANA schema-scoped actions", () =>
expect(sidebarDangerRunningExecutionId.value).toBe("");
expect(sidebarDangerRunningCancel.value).toBeNull();
});
+
+ it.each(actions)("records executed SQL into historyStore on $action success", async ({ action, sql }) => {
+ const addMock = vi.fn().mockResolvedValue(undefined);
+ const historyStore = { add: addMock };
+ const { feature } = runtime("", { db_type: "saphana" }, "saphana", historyStore);
+
+ await feature[action]();
+
+ expect(addMock).toHaveBeenCalledOnce();
+ expect(addMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ connection_id: "hana-1",
+ database: "",
+ sql,
+ success: true,
+ target: "ORDERS",
+ }),
+ );
+ });
+
+ it("records failed mutation into historyStore when execution fails", async () => {
+ const addMock = vi.fn().mockResolvedValue(undefined);
+ const historyStore = { add: addMock };
+ const { feature } = runtime("", { db_type: "saphana" }, "saphana", historyStore);
+ mocks.executeWithProductionGuard.mockRejectedValueOnce(new Error("Database write error"));
+
+ await feature.confirmDropTable();
+
+ expect(addMock).toHaveBeenCalledOnce();
+ expect(addMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ connection_id: "hana-1",
+ database: "",
+ sql: 'DROP TABLE "APP"."ORDERS";',
+ success: false,
+ error: "Database write error",
+ target: "ORDERS",
+ }),
+ );
+ });
+
+ it("does not record into historyStore when production confirmation is declined", async () => {
+ const addMock = vi.fn().mockResolvedValue(undefined);
+ const historyStore = { add: addMock };
+ const { feature } = runtime("", { db_type: "saphana" }, "saphana", historyStore);
+ mocks.executeWithProductionGuard.mockResolvedValueOnce(undefined);
+
+ await feature.confirmDropTable();
+
+ expect(addMock).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/composables/useSidebarTableMutationRuntime.ts b/apps/desktop/src/composables/useSidebarTableMutationRuntime.ts
index 1b56d81a75..2547b72a49 100644
--- a/apps/desktop/src/composables/useSidebarTableMutationRuntime.ts
+++ b/apps/desktop/src/composables/useSidebarTableMutationRuntime.ts
@@ -24,6 +24,7 @@ import { isQueryTimeoutErrorMessage } from "@/lib/sql/queryError";
import { uuid } from "@/lib/common/utils";
import * as api from "@/lib/backend/api";
import { normalizeBackendError, type BackendError } from "@/lib/backend/errorUtils";
+import { recordTableMutationHistory, type TableMutationHistoryStore } from "@/lib/history/tableMutationHistory";
import {
sidebarDangerTarget,
sidebarDangerRunningExecutionId,
@@ -57,6 +58,7 @@ interface SidebarTableMutationRuntimeOptions {
executeWithProductionGuard: (node: Pick<TreeNode, "connectionId" | "database" | "schema">, sql: string, options?: { database?: string; schema?: string; executionId?: string; isCancelledBeforeDispatch?: () => boolean; markDispatched?: () => void }) => Promise<unknown>;
closeDroppedTableObjectTabsForNode: (node: TreeNode) => void;
refreshMutatedTableDataTabsForNode: (node: TreeNode) => Promise<void>;
+ historyStore?: TableMutationHistoryStore;
}
export function useSidebarTableMutationRuntime(options: SidebarTableMutationRuntimeOptions) {
@@ -458,9 +460,13 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRunt
const { node, buildSql, onSuccess } = config;
if (!node.connectionId || node.database == null) return;
const { executionId, isCancelledBeforeDispatch, markDispatched, wasCancelled, cancelConfirmed, waitForCancelConfirmation, markHandedOff } = beginDangerRunningExecution(node.label);
+ const start = Date.now();
+ let executedSql = "";
+ let successRecorded = false;
try {
await connectionStore.ensureConnected(node.connectionId);
const sql = await buildSql();
+ executedSql = sql;
if (isCancelledBeforeDispatch()) throw new Error(DANGER_OPERATION_CANCELLED_BEFORE_DISPATCH_MESSAGE);
const executed = await options.executeWithProductionGuard(node, sql, { database: node.database, schema: node.schema, executionId, isCancelledBeforeDispatch, markDispatched });
if (executed === undefined) {
@@ -469,6 +475,18 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRunt
endDangerRunningExecution();
return;
}
+ if (options.historyStore) {
+ await recordTableMutationHistory(options.historyStore, {
+ connectionId: node.connectionId,
+ connectionName: connectionStore.getConfig(node.connectionId)?.name,
+ database: node.database,
+ sql,
+ elapsedMs: Date.now() - start,
+ success: true,
+ target: node.label,
+ }).catch((err) => console.warn("[DBX] failed to record table mutation history", err));
+ successRecorded = true;
+ }
await onSuccess(node);
endDangerRunningExecution();
} catch (error: any) {
@@ -476,6 +494,18 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRunt
const backendError = normalizeBackendError(error) ?? undefined;
const cancellationWasRequested = wasCancelled();
const cancellationWasConfirmed = cancelConfirmed() || (cancellationWasRequested && (await waitForCancelConfirmation()));
+ if (executedSql && !successRecorded && options.historyStore && !cancellationWasRequested && !cancellationWasConfirmed && !isCancelledBeforeDispatch()) {
+ await recordTableMutationHistory(options.historyStore, {
+ connectionId: node.connectionId,
+ connectionName: connectionStore.getConfig(node.connectionId)?.name,
+ database: node.database,
+ sql: executedSql,
+ elapsedMs: Date.now() - start,
+ success: false,
+ error: message,
+ target: node.label,
+ }).catch((err) => console.warn("[DBX] failed to record table mutation history", err));
+ }
toastDangerOperationError(node.label, message, cancellationWasRequested, cancellationWasConfirmed, backendError);
if (cancellationWasConfirmed || !isQueryTimeoutErrorMessage(message, backendError)) {
endDangerRunningExecution();
diff --git a/apps/desktop/src/lib/history/__tests__/tableMutationHistory.spec.ts b/apps/desktop/src/lib/history/__tests__/tableMutationHistory.spec.ts
new file mode 100644
index 0000000000..4470f5f884
--- /dev/null
+++ b/apps/desktop/src/lib/history/__tests__/tableMutationHistory.spec.ts
@@ -0,0 +1,180 @@
+import { describe, expect, it, vi } from "vitest";
+import { recordTableMutationHistory, type TableMutationHistoryStore } from "@/lib/history/tableMutationHistory";
+import { primarySqlOperation } from "@/lib/history/historyActivityKind";
+
+describe("tableMutationHistory", () => {
+ it("records drop table operation to history store", async () => {
+ const addMock = vi.fn().mockResolvedValue(undefined);
+ const store: TableMutationHistoryStore = { add: addMock };
+
+ await recordTableMutationHistory(store, {
+ connectionId: "conn-1",
+ connectionName: "Production DB",
+ database: "main",
+ sql: "DROP TABLE users;",
+ elapsedMs: 120,
+ success: true,
+ target: "users",
+ });
+
+ expect(addMock).toHaveBeenCalledOnce();
+ expect(addMock).toHaveBeenCalledWith({
+ connection_id: "conn-1",
+ connection_name: "Production DB",
+ database: "main",
+ sql: "DROP TABLE users;",
+ execution_time_ms: 120,
+ success: true,
+ error: undefined,
+ activity_kind: "schema_change",
+ operation: "DROP",
+ target: "users",
+ affected_rows: undefined,
+ });
+ });
+
+ it("records truncate table operation as data_change", async () => {
+ const addMock = vi.fn().mockResolvedValue(undefined);
+ const store: TableMutationHistoryStore = { add: addMock };
+
+ await recordTableMutationHistory(store, {
+ connectionId: "conn-1",
+ connectionName: "Production DB",
+ database: "analytics",
+ sql: "TRUNCATE TABLE event_logs;",
+ elapsedMs: 45,
+ success: true,
+ target: "event_logs",
+ });
+
+ expect(addMock).toHaveBeenCalledOnce();
+ expect(addMock).toHaveBeenCalledWith({
+ connection_id: "conn-1",
+ connection_name: "Production DB",
+ database: "analytics",
+ sql: "TRUNCATE TABLE event_logs;",
+ execution_time_ms: 45,
+ success: true,
+ error: undefined,
+ activity_kind: "data_change",
+ operation: "TRUNCATE",
+ target: "event_logs",
+ affected_rows: undefined,
+ });
+ });
+
+ it("records empty table (delete) operation as data_change", async () => {
+ const addMock = vi.fn().mockResolvedValue(undefined);
+ const store: TableMutationHistoryStore = { add: addMock };
+
+ await recordTableMutationHistory(store, {
+ connectionId: "conn-1",
+ database: "testdb",
+ sql: "DELETE FROM session_cache;",
+ elapsedMs: 15,
+ success: true,
+ target: "session_cache",
+ affectedRows: 100,
+ });
+
+ expect(addMock).toHaveBeenCalledOnce();
+ expect(addMock).toHaveBeenCalledWith({
+ connection_id: "conn-1",
+ connection_name: "",
+ database: "testdb",
+ sql: "DELETE FROM session_cache;",
+ execution_time_ms: 15,
+ success: true,
+ error: undefined,
+ activity_kind: "data_change",
+ operation: "DELETE",
+ target: "session_cache",
+ affected_rows: 100,
+ });
+ });
+
+ it("records failed mutations with error message and clears affected_rows", async () => {
+ const addMock = vi.fn().mockResolvedValue(undefined);
+ const store: TableMutationHistoryStore = { add: addMock };
+
+ await recordTableMutationHistory(store, {
+ connectionId: "conn-1",
+ database: "testdb",
+ sql: "DROP TABLE protected_table;",
+ elapsedMs: 8,
+ success: false,
+ error: "Permission denied",
+ target: "protected_table",
+ affectedRows: 5,
+ });
+
+ expect(addMock).toHaveBeenCalledOnce();
+ expect(addMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ success: false,
+ error: "Permission denied",
+ affected_rows: undefined,
+ }),
+ );
+ });
+
+ it("handles batch multi-statement SQL", async () => {
+ const addMock = vi.fn().mockResolvedValue(undefined);
+ const store: TableMutationHistoryStore = { add: addMock };
+
+ await recordTableMutationHistory(store, {
+ connectionId: "conn-1",
+ database: "testdb",
+ sql: "TRUNCATE TABLE t1;\nTRUNCATE TABLE t2;",
+ elapsedMs: 50,
+ success: true,
+ target: "t1, t2",
+ });
+
+ expect(addMock).toHaveBeenCalledOnce();
+ expect(addMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ activity_kind: "data_change",
+ operation: "TRUNCATE",
+ target: "t1, t2",
+ }),
+ );
+ });
+
+ it("safely ignores undefined store, empty SQL, or empty connectionId", async () => {
+ const addMock = vi.fn().mockResolvedValue(undefined);
+ const store: TableMutationHistoryStore = { add: addMock };
+
+ await recordTableMutationHistory(undefined, {
+ connectionId: "conn-1",
+ database: "db",
+ sql: "DROP TABLE t1;",
+ });
+ expect(addMock).not.toHaveBeenCalled();
+
+ await recordTableMutationHistory(store, {
+ connectionId: "conn-1",
+ database: "db",
+ sql: " \n ",
+ });
+ expect(addMock).not.toHaveBeenCalled();
+
+ await recordTableMutationHistory(store, {
+ connectionId: "",
+ database: "db",
+ sql: "DROP TABLE t1;",
+ });
+ expect(addMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("primarySqlOperation", () => {
+ it("extracts primary SQL verb accurately", () => {
+ expect(primarySqlOperation("DROP TABLE t1")).toBe("DROP");
+ expect(primarySqlOperation("truncate table t1")).toBe("TRUNCATE");
+ expect(primarySqlOperation("DELETE FROM t1")).toBe("DELETE");
+ expect(primarySqlOperation("-- leading comment\nDROP TABLE t1")).toBe("DROP");
+ expect(primarySqlOperation("/* block comment */ ALTER TABLE t1")).toBe("ALTER");
+ expect(primarySqlOperation("")).toBe("SQL");
+ });
+});
diff --git a/apps/desktop/src/lib/history/historyActivityKind.ts b/apps/desktop/src/lib/history/historyActivityKind.ts
index cd8c831308..f4cfb7ad61 100644
--- a/apps/desktop/src/lib/history/historyActivityKind.ts
+++ b/apps/desktop/src/lib/history/historyActivityKind.ts
@@ -41,3 +41,9 @@ export function resolveHistoryActivityKind(entry: HistoryActivitySource): Histor
return entry.sql ? classifySqlActivityKind(entry.sql) : "query";
}
+
+export function primarySqlOperation(sql: string): string {
+ const statements = statementsFor(sql);
+ const first = statements[0];
+ return first?.match(/^([a-z]+)/i)?.[1]?.toUpperCase() || "SQL";
+}
diff --git a/apps/desktop/src/lib/history/tableMutationHistory.ts b/apps/desktop/src/lib/history/tableMutationHistory.ts
new file mode 100644
index 0000000000..b886484669
--- /dev/null
+++ b/apps/desktop/src/lib/history/tableMutationHistory.ts
@@ -0,0 +1,50 @@
+import { getActivePinia } from "pinia";
+import type { HistoryEntry } from "@/lib/backend/api";
+import { classifySqlActivityKind, primarySqlOperation } from "@/lib/history/historyActivityKind";
+import { useHistoryStore } from "@/stores/historyStore";
+
+export interface RecordTableMutationHistoryOptions {
+ connectionId: string;
+ connectionName?: string;
+ database: string;
+ sql: string;
+ elapsedMs?: number;
+ success?: boolean;
+ error?: string;
+ target?: string;
+ affectedRows?: number;
+}
+
+export type TableMutationHistoryStore = {
+ add: (entry: Omit<HistoryEntry, "id" | "executed_at">) => Promise<void>;
+};
+
+export function getTableMutationHistoryStoreOrNull(): TableMutationHistoryStore | null {
+ try {
+ if (!getActivePinia()) return null;
+ return useHistoryStore();
+ } catch {
+ return null;
+ }
+}
+
+export async function recordTableMutationHistory(historyStore: TableMutationHistoryStore | undefined | null, options: RecordTableMutationHistoryOptions): Promise<void> {
+ if (!historyStore) return;
+ const sql = options.sql.trim();
+ if (!sql || !options.connectionId) return;
+
+ const success = options.success ?? true;
+ await historyStore.add({
+ connection_id: options.connectionId,
+ connection_name: options.connectionName || "",
+ database: options.database,
+ sql,
+ execution_time_ms: Math.max(0, options.elapsedMs ?? 0),
+ success,
+ error: options.error,
+ activity_kind: classifySqlActivityKind(sql),
+ operation: primarySqlOperation(sql),
+ target: options.target,
+ affected_rows: success ? options.affectedRows : undefined,
+ });
+}