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 { useSettingsStore } from "@/stores/settingsStore";
import { formatSidebarTableNamesForCopy, type SidebarTableCopyTarget } from "@/lib/sidebar/sidebarTableNameCopy"; import { formatSidebarTableNamesForCopy, type SidebarTableCopyTarget } from "@/lib/sidebar/sidebarTableNameCopy";
import { useQueryStore } from "@/stores/queryStore"; import { useQueryStore } from "@/stores/queryStore";
import { getTableMutationHistoryStoreOrNull, recordTableMutationHistory } from "@/lib/history/tableMutationHistory";
import QueryEditor from "@/components/editor/QueryEditor.vue"; import QueryEditor from "@/components/editor/QueryEditor.vue";
import MySqlEventEditor from "@/components/objects/MySqlEventEditor.vue"; import MySqlEventEditor from "@/components/objects/MySqlEventEditor.vue";
import { sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter"; import { sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
@@ -1845,10 +1846,24 @@ async function confirmRename() {
async function confirmDrop() { async function confirmDrop() {
if (!dropTarget.value) return; if (!dropTarget.value) return;
const row = dropTarget.value; const row = dropTarget.value;
let executedSql = "";
const start = Date.now();
let successRecorded = false;
try { try {
const sql = dropPreviewSql.value || (await buildDropSqlForRow(row, { cascade: canDropTargetCascade.value && dropTableCascade.value })); 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)); const executed = await executeObjectBrowserSqlWithProductionGuard(sql, () => api.executeQuery(props.connection.id, props.database, sql));
if (!executed) return; 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"; 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 })); toast(t(successKey, { name: row.name }));
const cacheSchema = row.schema || selectedSchema.value || props.database; const cacheSchema = row.schema || selectedSchema.value || props.database;
@@ -1859,6 +1874,18 @@ async function confirmDrop() {
await reload(); await reload();
await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, row.schema || selectedSchema.value); await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, row.schema || selectedSchema.value);
} catch (e: any) { } 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); toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
} }
dropTarget.value = null; dropTarget.value = null;
@@ -2105,8 +2132,12 @@ function requestBatchDropTables() {
async function confirmBatchDropTables() { async function confirmBatchDropTables() {
if (batchDropExecuting.value) return; if (batchDropExecuting.value) return;
batchDropExecuting.value = true; batchDropExecuting.value = true;
let batchSql = "";
let batchDropRecorded = false;
let targets: ObjectBrowserRow[] = [];
const start = Date.now();
try { try {
const targets = await fetchSortedTableRowsForDrop(); targets = await fetchSortedTableRowsForDrop();
if (targets.length === 0) return; if (targets.length === 0) return;
batchDropProgress.value = { completed: 0, total: targets.length }; batchDropProgress.value = { completed: 0, total: targets.length };
const useCascade = canBatchDropCascade.value && batchDropCascade.value; const useCascade = canBatchDropCascade.value && batchDropCascade.value;
@@ -2116,7 +2147,7 @@ async function confirmBatchDropTables() {
sql: await buildDropTableSql(tableAdminSqlOptions(target, { cascade: useCascade })), 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, () => const result = await executeObjectBrowserSqlWithProductionGuard(batchSql, () =>
runBatchTableDrop({ runBatchTableDrop({
databaseType: effectiveDatabaseType.value, databaseType: effectiveDatabaseType.value,
@@ -2130,6 +2161,18 @@ async function confirmBatchDropTables() {
); );
if (!result) return; 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); for (const row of result.succeeded) closeDroppedTableObjectTabsForRow(row);
if (result.succeeded.length > 0) { if (result.succeeded.length > 0) {
removePinnedObjectBrowserRows(result.succeeded); removePinnedObjectBrowserRows(result.succeeded);
@@ -2140,6 +2183,18 @@ async function confirmBatchDropTables() {
if (result.failed) throw result.failed; if (result.failed) throw result.failed;
toast(t("objects.batchDropSuccess", { count: result.succeeded.length })); toast(t("objects.batchDropSuccess", { count: result.succeeded.length }));
} catch (e: any) { } 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); toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
} finally { } finally {
batchDropExecuting.value = false; batchDropExecuting.value = false;
@@ -2191,6 +2246,9 @@ async function refreshMutatedTableDataTabsForRows(rows: readonly ObjectBrowserRo
async function confirmBatchTruncateTables() { async function confirmBatchTruncateTables() {
const targets = [...selectedTableRows.value]; const targets = [...selectedTableRows.value];
if (targets.length === 0) return; if (targets.length === 0) return;
let batchSql = "";
const start = Date.now();
let successRecorded = false;
try { try {
const useCascade = canBatchTruncateCascade.value && batchTruncateCascade.value; const useCascade = canBatchTruncateCascade.value && batchTruncateCascade.value;
const statements = await Promise.all( const statements = await Promise.all(
@@ -2199,7 +2257,8 @@ async function confirmBatchTruncateTables() {
sql: await buildTruncateTableSql(tableAdminSqlOptions(row, { cascade: useCascade })), 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( await runBatchTableTruncate(
statements, statements,
async ({ sql }) => { async ({ sql }) => {
@@ -2210,12 +2269,34 @@ async function confirmBatchTruncateTables() {
return true; return true;
}); });
if (!executed) return; 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 })); toast(t("objects.batchTruncateSuccess", { count: targets.length }));
clearTableSelection(); clearTableSelection();
showBatchTruncateConfirm.value = false; showBatchTruncateConfirm.value = false;
await reload(); await reload();
await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, selectedSchema.value); await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, selectedSchema.value);
} catch (e: any) { } 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); toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
} }
} }
@@ -2245,6 +2326,7 @@ function requestBatchEmptyTables() {
async function confirmBatchEmptyTables() { async function confirmBatchEmptyTables() {
const plan = batchEmptyPlan.value.slice(); const plan = batchEmptyPlan.value.slice();
if (plan.length === 0) return; if (plan.length === 0) return;
const start = Date.now();
const asynchronousMutation = effectiveDatabaseType.value === "clickhouse"; const asynchronousMutation = effectiveDatabaseType.value === "clickhouse";
const reviewSql = plan.map(({ sql }) => sql).join(";\n"); const reviewSql = plan.map(({ sql }) => sql).join(";\n");
const result = await executeObjectBrowserSqlWithProductionGuard(reviewSql, () => { const result = await executeObjectBrowserSqlWithProductionGuard(reviewSql, () => {
@@ -2253,6 +2335,16 @@ async function confirmBatchEmptyTables() {
}); });
}); });
if (!result) return; 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) { for (const failure of result.failed) {
console.error(`Failed to empty table "${failure.target.target.name}":`, failure.error); console.error(`Failed to empty table "${failure.target.target.name}":`, failure.error);
} }
@@ -2846,13 +2938,39 @@ function requestTruncateTable(row: ObjectBrowserRow) {
async function confirmTruncateTable() { async function confirmTruncateTable() {
const row = truncateTarget.value; const row = truncateTarget.value;
if (!row) return; if (!row) return;
let executedSql = "";
const start = Date.now();
let successRecorded = false;
try { try {
const sql = truncatePreviewSql.value || (await buildTruncateTableSql(tableAdminSqlOptions(row, { cascade: canTruncateTargetCascade.value && truncateTableCascade.value }))); 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)); const executed = await executeObjectBrowserSqlWithProductionGuard(sql, () => api.executeQuery(props.connection.id, props.database, sql));
if (!executed) return; 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 })); toast(t("contextMenu.truncateTableSuccess", { name: row.name }));
await refreshMutatedTableDataTabsForRows([row]); await refreshMutatedTableDataTabsForRows([row]);
} catch (e: any) { } 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); toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
} }
truncateTarget.value = null; truncateTarget.value = null;
@@ -2921,13 +3039,39 @@ function requestEmptyTable(row: ObjectBrowserRow) {
async function confirmEmptyTable() { async function confirmEmptyTable() {
const row = emptyTarget.value; const row = emptyTarget.value;
if (!row) return; if (!row) return;
let executedSql = "";
const start = Date.now();
let successRecorded = false;
try { try {
const sql = emptyPreviewSql.value || (await buildEmptyTableSql(tableAdminSqlOptions(row))); const sql = emptyPreviewSql.value || (await buildEmptyTableSql(tableAdminSqlOptions(row)));
executedSql = sql;
const executed = await executeObjectBrowserSqlWithProductionGuard(sql, () => api.executeQuery(props.connection.id, props.database, sql)); const executed = await executeObjectBrowserSqlWithProductionGuard(sql, () => api.executeQuery(props.connection.id, props.database, sql));
if (!executed) return; 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 })); toast(t("contextMenu.emptyTableSuccess", { name: row.name }));
await refreshMutatedTableDataTabsForRows([row]); await refreshMutatedTableDataTabsForRows([row]);
} catch (e: any) { } 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); toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
} }
emptyTarget.value = null; emptyTarget.value = null;
@@ -70,6 +70,7 @@ import {
} from "@lucide/vue"; } from "@lucide/vue";
import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue"; import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { CONNECTION_ATTEMPT_CANCELLED_MESSAGE, useConnectionStore } from "@/stores/connectionStore"; import { CONNECTION_ATTEMPT_CANCELLED_MESSAGE, useConnectionStore } from "@/stores/connectionStore";
import { getTableMutationHistoryStoreOrNull, recordTableMutationHistory } from "@/lib/history/tableMutationHistory";
import { useQueryStore } from "@/stores/queryStore"; import { useQueryStore } from "@/stores/queryStore";
import { useSettingsStore } from "@/stores/settingsStore"; import { useSettingsStore } from "@/stores/settingsStore";
import { useSavedSqlStore } from "@/stores/savedSqlStore"; import { useSavedSqlStore } from "@/stores/savedSqlStore";
@@ -682,6 +683,9 @@ const {
executeWithProductionGuard: executeTreeNodeSqlWithProductionGuard, executeWithProductionGuard: executeTreeNodeSqlWithProductionGuard,
closeDroppedTableObjectTabsForNode, closeDroppedTableObjectTabsForNode,
refreshMutatedTableDataTabsForNode, refreshMutatedTableDataTabsForNode,
historyStore: {
add: (entry) => getTableMutationHistoryStoreOrNull()?.add(entry) ?? Promise.resolve(),
},
}); });
const batchDropProgress = ref({ completed: 0, total: 0 }); const batchDropProgress = ref({ completed: 0, total: 0 });
@@ -3530,6 +3534,7 @@ async function confirmBatchDrop() {
}), }),
); );
const batchSql = plan.map(({ sql }) => sql).join(";\n"); const batchSql = plan.map(({ sql }) => sql).join(";\n");
const startTime = Date.now();
const result = await executeWithProductionSqlGuard({ const result = await executeWithProductionSqlGuard({
connection: connectionStore.getConfig(first.connectionId!), connection: connectionStore.getConfig(first.connectionId!),
database: first.database!, database: first.database!,
@@ -3548,6 +3553,17 @@ async function confirmBatchDrop() {
}); });
if (!result) return; 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) { for (const target of result.succeeded) {
closeDroppedTableObjectTabsForNode(target); closeDroppedTableObjectTabsForNode(target);
connectionStore.removeTreeNode(target.id); connectionStore.removeTreeNode(target.id);
@@ -3564,7 +3580,22 @@ async function confirmBatchDrop() {
await connectionStore.ensureConnected(target.connectionId); await connectionStore.ensureConnected(target.connectionId);
const sql = await dropSqlForTreeNode(target, { cascade: useCascade }); const sql = await dropSqlForTreeNode(target, { cascade: useCascade });
if (!sql) continue; 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); closeDroppedTableObjectTabsForNode(target);
// Remove immediately so a later failure cannot leave dropped objects in the tree. // Remove immediately so a later failure cannot leave dropped objects in the tree.
connectionStore.removeTreeNode(target.id); connectionStore.removeTreeNode(target.id);
@@ -3595,8 +3626,19 @@ async function confirmBatchTruncate() {
await connectionStore.ensureConnected(target.connectionId); await connectionStore.ensureConnected(target.connectionId);
const sql = await truncateSqlForTreeNode(target, { cascade: useCascade }); const sql = await truncateSqlForTreeNode(target, { cascade: useCascade });
if (!sql) return false; if (!sql) return false;
const startTime = Date.now();
const result = await executeTreeNodeSqlWithProductionGuard(target, sql, { database: target.database, schema: target.schema }); 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, refreshMutatedTableDataTabsForNodes,
); );
@@ -3616,7 +3658,22 @@ async function confirmBatchEmpty() {
await connectionStore.ensureConnected(target.connectionId); await connectionStore.ensureConnected(target.connectionId);
const sql = await emptySqlForTreeNode(target); const sql = await emptySqlForTreeNode(target);
if (!sql) throw new Error("Empty table SQL is unavailable"); 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) { for (const failure of result.failed) {
console.error(`Failed to empty table "${failure.target.label}":`, failure.error); console.error(`Failed to empty table "${failure.target.label}":`, failure.error);
@@ -49,7 +49,7 @@ function tableNode(database: string | null | undefined): TreeNode {
} as 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 node = tableNode(database);
const activeNode = shallowRef(node); const activeNode = shallowRef(node);
const connectionStore = { const connectionStore = {
@@ -66,6 +66,7 @@ function runtime(database: string | null | undefined, config: Pick<ConnectionCon
executeWithProductionGuard: mocks.executeWithProductionGuard, executeWithProductionGuard: mocks.executeWithProductionGuard,
closeDroppedTableObjectTabsForNode: mocks.closeDroppedTableObjectTabsForNode, closeDroppedTableObjectTabsForNode: mocks.closeDroppedTableObjectTabsForNode,
refreshMutatedTableDataTabsForNode: mocks.refreshMutatedTableDataTabsForNode, refreshMutatedTableDataTabsForNode: mocks.refreshMutatedTableDataTabsForNode,
historyStore,
}); });
return { feature, node }; return { feature, node };
} }
@@ -456,4 +457,55 @@ describe("useSidebarTableMutationRuntime SAP HANA schema-scoped actions", () =>
expect(sidebarDangerRunningExecutionId.value).toBe(""); expect(sidebarDangerRunningExecutionId.value).toBe("");
expect(sidebarDangerRunningCancel.value).toBeNull(); 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();
});
}); });
@@ -24,6 +24,7 @@ import { isQueryTimeoutErrorMessage } from "@/lib/sql/queryError";
import { uuid } from "@/lib/common/utils"; import { uuid } from "@/lib/common/utils";
import * as api from "@/lib/backend/api"; import * as api from "@/lib/backend/api";
import { normalizeBackendError, type BackendError } from "@/lib/backend/errorUtils"; import { normalizeBackendError, type BackendError } from "@/lib/backend/errorUtils";
import { recordTableMutationHistory, type TableMutationHistoryStore } from "@/lib/history/tableMutationHistory";
import { import {
sidebarDangerTarget, sidebarDangerTarget,
sidebarDangerRunningExecutionId, 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>; 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; closeDroppedTableObjectTabsForNode: (node: TreeNode) => void;
refreshMutatedTableDataTabsForNode: (node: TreeNode) => Promise<void>; refreshMutatedTableDataTabsForNode: (node: TreeNode) => Promise<void>;
historyStore?: TableMutationHistoryStore;
} }
export function useSidebarTableMutationRuntime(options: SidebarTableMutationRuntimeOptions) { export function useSidebarTableMutationRuntime(options: SidebarTableMutationRuntimeOptions) {
@@ -458,9 +460,13 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRunt
const { node, buildSql, onSuccess } = config; const { node, buildSql, onSuccess } = config;
if (!node.connectionId || node.database == null) return; if (!node.connectionId || node.database == null) return;
const { executionId, isCancelledBeforeDispatch, markDispatched, wasCancelled, cancelConfirmed, waitForCancelConfirmation, markHandedOff } = beginDangerRunningExecution(node.label); const { executionId, isCancelledBeforeDispatch, markDispatched, wasCancelled, cancelConfirmed, waitForCancelConfirmation, markHandedOff } = beginDangerRunningExecution(node.label);
const start = Date.now();
let executedSql = "";
let successRecorded = false;
try { try {
await connectionStore.ensureConnected(node.connectionId); await connectionStore.ensureConnected(node.connectionId);
const sql = await buildSql(); const sql = await buildSql();
executedSql = sql;
if (isCancelledBeforeDispatch()) throw new Error(DANGER_OPERATION_CANCELLED_BEFORE_DISPATCH_MESSAGE); 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 }); const executed = await options.executeWithProductionGuard(node, sql, { database: node.database, schema: node.schema, executionId, isCancelledBeforeDispatch, markDispatched });
if (executed === undefined) { if (executed === undefined) {
@@ -469,6 +475,18 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRunt
endDangerRunningExecution(); endDangerRunningExecution();
return; 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); await onSuccess(node);
endDangerRunningExecution(); endDangerRunningExecution();
} catch (error: any) { } catch (error: any) {
@@ -476,6 +494,18 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRunt
const backendError = normalizeBackendError(error) ?? undefined; const backendError = normalizeBackendError(error) ?? undefined;
const cancellationWasRequested = wasCancelled(); const cancellationWasRequested = wasCancelled();
const cancellationWasConfirmed = cancelConfirmed() || (cancellationWasRequested && (await waitForCancelConfirmation())); 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); toastDangerOperationError(node.label, message, cancellationWasRequested, cancellationWasConfirmed, backendError);
if (cancellationWasConfirmed || !isQueryTimeoutErrorMessage(message, backendError)) { if (cancellationWasConfirmed || !isQueryTimeoutErrorMessage(message, backendError)) {
endDangerRunningExecution(); endDangerRunningExecution();
@@ -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");
});
});
@@ -41,3 +41,9 @@ export function resolveHistoryActivityKind(entry: HistoryActivitySource): Histor
return entry.sql ? classifySqlActivityKind(entry.sql) : "query"; 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";
}
@@ -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,
});
}