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

This commit is contained in:
lxk955 authored and GitHub committed 2026-10-04 03:29:33 +08:00
1 parent 238cf81370
commit a9990d5fdb
7 files changed
+526 -7

No files matched your search

@@ -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;
@@ -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);