feat(grid): add conditional bulk updates for MySQL

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-08-21 01:04:16 +08:00
1 parent 10d1509d92
commit a7edb8f8db
29 files changed
+1813 -85

No files matched your search

@@ -7,6 +7,8 @@ const mocks = vi.hoisted(() => ({
getConfig: vi.fn(),
prepareDataGridSave: vi.fn(),
executeBatch: vi.fn(),
executeConditionalUpdate: vi.fn(),
cancelConditionalUpdate: vi.fn(),
executeInTransaction: vi.fn(),
addHistory: vi.fn(),
}));
@@ -14,6 +16,8 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/lib/backend/api", () => ({
prepareDataGridSave: mocks.prepareDataGridSave,
executeBatch: mocks.executeBatch,
executeConditionalUpdate: mocks.executeConditionalUpdate,
cancelConditionalUpdate: mocks.cancelConditionalUpdate,
executeInTransaction: mocks.executeInTransaction,
}));
vi.mock("@/stores/connectionStore", () => ({
@@ -366,6 +370,8 @@ describe("useDataGridEditor saveChanges reload", () => {
beforeEach(() => {
mocks.prepareDataGridSave.mockReset();
mocks.executeBatch.mockReset();
mocks.executeConditionalUpdate.mockReset();
mocks.cancelConditionalUpdate.mockReset();
mocks.executeInTransaction.mockReset();
mocks.addHistory.mockReset();
mocks.getConfig.mockReset();
@@ -428,6 +434,132 @@ describe("useDataGridEditor saveChanges reload", () => {
expect(emit).toHaveBeenCalledWith("reload", undefined, "", undefined, undefined, 100, 0);
});
it("executes a conditional update immediately, records affected rows, and reloads", async () => {
mocks.getConfig.mockReturnValue({ id: "connection-1", name: "Local MySQL", db_type: "mysql" });
mocks.executeConditionalUpdate.mockResolvedValue({ affected_rows: 7 });
const prepareFullReload = vi.fn();
const { editor, emit } = createSaveTestEditor({ prepareFullReload });
const statement = "UPDATE `app`.`orders_test` SET `status` = 'shipped' WHERE (`status` = 'pending');";
await expect(editor.executeConditionalUpdate(statement)).resolves.toEqual({ affectedRows: 7 });
expect(mocks.executeConditionalUpdate).toHaveBeenCalledWith("connection-1", "app", statement, undefined, expect.any(String));
expect(mocks.addHistory).toHaveBeenCalledWith(
expect.objectContaining({
connection_id: "connection-1",
connection_name: "Local MySQL",
sql: statement,
success: true,
operation: "UPDATE",
affected_rows: 7,
}),
);
expect(JSON.parse(mocks.addHistory.mock.calls[0][0].details_json)).toMatchObject({ conditional_update: true, statement_count: 1 });
expect(prepareFullReload).toHaveBeenCalledTimes(1);
expect(emit).toHaveBeenCalledWith("reload", undefined, "", undefined, undefined, 100, 0);
});
it("unlocks, records, and reloads after a terminal conditional update failure", async () => {
const sqlError = Object.assign(new Error("Duplicate entry '1' for key 'PRIMARY'"), {
backendError: {
version: 1,
code: "DBX-JDBC-4001",
messageKey: "backendErrors.jdbc.sqlFailed",
messageParams: { stage: "execute" },
source: "jdbc_agent",
operationOutcome: "unknown",
diagnostics: { category: "sql", stage: "execute" },
},
});
mocks.executeConditionalUpdate.mockRejectedValue(sqlError);
const prepareFullReload = vi.fn();
const { editor, emit } = createSaveTestEditor({ prepareFullReload });
const statement = "UPDATE `app`.`orders_test` SET `id` = 1 WHERE (`status` = 'pending');";
await expect(editor.executeConditionalUpdate(statement)).resolves.toBeNull();
expect(editor.isConditionalUpdateActive.value).toBe(false);
expect(editor.saveError.value).toBe("Duplicate entry '1' for key 'PRIMARY'");
expect(mocks.cancelConditionalUpdate).not.toHaveBeenCalled();
expect(mocks.addHistory).toHaveBeenCalledWith(
expect.objectContaining({
sql: statement,
success: false,
error: "Duplicate entry '1' for key 'PRIMARY'",
affected_rows: undefined,
}),
);
expect(JSON.parse(mocks.addHistory.mock.calls[0][0].details_json)).toMatchObject({ conditional_update: true, execution_outcome: "failed" });
expect(prepareFullReload).toHaveBeenCalledTimes(1);
expect(emit).toHaveBeenCalledWith("reload", undefined, "", undefined, undefined, 100, 0);
});
it("refuses a conditional update while row edits are pending", async () => {
const { editor, emit } = createSaveTestEditor();
editor.dirtyRows.value = new Map([[0, new Map([[1, "shipped"]])]]);
await expect(editor.executeConditionalUpdate("UPDATE orders_test SET status = 'shipped' WHERE id > 0;")).resolves.toBeNull();
expect(mocks.executeConditionalUpdate).not.toHaveBeenCalled();
expect(mocks.addHistory).not.toHaveBeenCalled();
expect(emit).not.toHaveBeenCalled();
expect(editor.saveError.value).not.toBe("");
});
it("keeps a timed-out conditional update cancellable without recording a failed update", async () => {
mocks.executeConditionalUpdate.mockRejectedValue(new Error("Query timed out after 30 seconds"));
mocks.cancelConditionalUpdate.mockResolvedValue({ requested: true, terminal: true });
const { editor, emit } = createSaveTestEditor();
await expect(editor.executeConditionalUpdate("UPDATE orders_test SET status = 'shipped' WHERE id > 0;")).resolves.toBeNull();
expect(editor.isConditionalUpdateActive.value).toBe(true);
expect(mocks.addHistory).not.toHaveBeenCalled();
expect(emit).not.toHaveBeenCalled();
await expect(editor.cancelConditionalUpdate()).resolves.toBe(true);
expect(editor.isConditionalUpdateActive.value).toBe(false);
expect(mocks.cancelConditionalUpdate).toHaveBeenCalledWith(expect.any(String));
expect(emit).toHaveBeenCalledWith("reload", undefined, "", undefined, undefined, 100, 0);
});
it("keeps a timed-out conditional update locked until cancellation reports a terminal state", async () => {
vi.useFakeTimers();
mocks.executeConditionalUpdate.mockRejectedValue(new Error("Query timed out after 30 seconds"));
mocks.cancelConditionalUpdate.mockResolvedValue({ requested: true, terminal: false });
const { editor, emit } = createSaveTestEditor();
try {
await expect(editor.executeConditionalUpdate("UPDATE orders_test SET status = 'shipped' WHERE id > 0;")).resolves.toBeNull();
await expect(editor.cancelConditionalUpdate()).resolves.toBe(false);
expect(editor.isConditionalUpdateActive.value).toBe(true);
expect(emit).not.toHaveBeenCalled();
} finally {
vi.clearAllTimers();
vi.useRealTimers();
}
});
it("reloads a timed-out conditional update after a later terminal confirmation", async () => {
vi.useFakeTimers();
mocks.executeConditionalUpdate.mockRejectedValue(new Error("Query timed out after 30 seconds"));
mocks.cancelConditionalUpdate.mockResolvedValueOnce({ requested: true, terminal: false }).mockResolvedValueOnce({ requested: false, terminal: true });
const { editor, emit } = createSaveTestEditor();
try {
await expect(editor.executeConditionalUpdate("UPDATE orders_test SET status = 'shipped' WHERE id > 0;")).resolves.toBeNull();
await expect(editor.cancelConditionalUpdate()).resolves.toBe(false);
await vi.advanceTimersByTimeAsync(1_000);
expect(editor.isConditionalUpdateActive.value).toBe(false);
expect(mocks.cancelConditionalUpdate).toHaveBeenCalledTimes(2);
expect(emit).toHaveBeenCalledWith("reload", undefined, "", undefined, undefined, 100, 0);
} finally {
vi.clearAllTimers();
vi.useRealTimers();
}
});
it("does not reload when there are no pending changes to save", async () => {
const { editor, emit } = createSaveTestEditor();
@@ -1,4 +1,4 @@
import { ref, shallowRef, computed, nextTick, watch, getCurrentInstance, onActivated, onBeforeUnmount, onDeactivated, onMounted, toRaw, type ComputedRef, type Ref } from "vue";
import { ref, shallowRef, triggerRef, computed, nextTick, watch, getCurrentInstance, onActivated, onBeforeUnmount, onDeactivated, onMounted, toRaw, type ComputedRef, type Ref } from "vue";
import * as api from "@/lib/backend/api";
import type { CellValue } from "@/lib/dataGrid/cellValue";
import { coerceDataGridCellValue, dataGridCellEditorText } from "@/lib/dataGrid/dataGridCellCoercion";
@@ -14,6 +14,8 @@ import { assessProductionSql, productionContextForDatabase } from "@/lib/databas
import type { ColumnInfo, DatabaseType } from "@/types/database";
import { DBX_NEO4J_ELEMENT_ID_COLUMN, usesSyntheticRowIdKey } from "@/lib/table/tableEditing";
import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
import { normalizeBackendError } from "@/lib/backend/errorUtils";
import { uuid } from "@/lib/common/utils";
import i18n from "@/i18n";
interface RowItem {
@@ -32,6 +34,16 @@ export const DATA_GRID_QUICK_ENTRY_DRAFT_ROW_ID = Number.MIN_SAFE_INTEGER;
export const DATA_GRID_MAX_BATCH_INSERT_ROWS = 1000;
type RowKind = "none" | "existing" | "new" | "draft";
type ConditionalUpdateOutcome = "not-started" | "running" | "completed" | "failed" | "unknown";
interface ConditionalUpdateExecution {
executionId: string;
dispatched: boolean;
cancelRequested: boolean;
cancelling: boolean;
terminalCheckScheduled: boolean;
outcome: ConditionalUpdateOutcome;
}
export type DataGridAppendPastedRowsResult = { ok: true; rowCount: number } | { ok: false; reason: "not-editable" | "invalid-target" | "target-not-empty" | "empty-paste" | "readonly-column" };
@@ -321,6 +333,8 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
const transactionActive = ref(false);
const isSaving = ref(false);
const saveError = ref("");
const conditionalUpdateExecution = shallowRef<ConditionalUpdateExecution>();
const isConditionalUpdateActive = computed(() => conditionalUpdateExecution.value !== undefined);
const hasBackendSaveTarget = computed(() => !!connectionId.value && !!tableMeta.value);
const useTransaction = computed(() => editable.value && supportsDataGridTransaction(resolvedDatabaseType.value) && (!!customSaveHandler?.value || hasBackendSaveTarget.value));
@@ -613,7 +627,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
function canEditColumn(columnIndex: number): boolean {
const sources = sourceColumns.value;
return (!sources || sources[columnIndex] !== undefined) && !readonlyColumnIndexes.value?.has(columnIndex);
return !isConditionalUpdateActive.value && (!sources || sources[columnIndex] !== undefined) && !readonlyColumnIndexes.value?.has(columnIndex);
}
// --- Row data helpers ---
@@ -1005,6 +1019,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
function addRow() {
if (isConditionalUpdateActive.value) return;
pushUndoSnapshot();
rowStatusFilter.value = rowStatusFilterAfterAddingRow(rowStatusFilter.value);
newRows.value.push(result.value.columns.map(() => null));
@@ -1033,6 +1048,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
// positions). Returns the first inserted row's id, or undefined when the
// count was rejected.
function addRows(count: number, placement: GridNewRowPlacement | null = null): number | undefined {
if (isConditionalUpdateActive.value) return undefined;
if (!Number.isInteger(count) || count <= 0) return undefined;
const clampedCount = Math.min(count, DATA_GRID_MAX_BATCH_INSERT_ROWS);
const firstNewIndex = newRows.value.length;
@@ -1172,6 +1188,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
function cloneRows(rowIds: number[], resolvedValues?: ReadonlyMap<number, ReadonlyMap<number, CellValue>>) {
if (isConditionalUpdateActive.value) return;
const rowsToClone = rowIds.map((rowId) => getRowItem(rowId)).filter(Boolean) as RowItem[];
if (rowsToClone.length === 0) return;
pushUndoSnapshot();
@@ -1190,6 +1207,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
function applyDeleteRows(rowIds: number[]) {
if (isConditionalUpdateActive.value) return;
const items = rowIds.map((rowId) => getRowItem(rowId)).filter((item): item is RowItem => !!item);
if (items.length === 0) return;
@@ -1275,6 +1293,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
);
function restoreRow(rowId: number) {
if (isConditionalUpdateActive.value) return;
const item = getRowItem(rowId);
if (item?.sourceIndex !== undefined && deletedRows.value.has(item.sourceIndex)) {
pushUndoSnapshot();
@@ -1285,6 +1304,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
function restoreRows(rowIds: number[]) {
if (isConditionalUpdateActive.value) return;
const sourceIndexes = rowIds.map((rowId) => getRowItem(rowId)?.sourceIndex).filter((sourceIndex): sourceIndex is number => sourceIndex !== undefined && deletedRows.value.has(sourceIndex));
if (sourceIndexes.length === 0) return;
pushUndoSnapshot();
@@ -1458,11 +1478,173 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
return message;
}
async function recordConditionalUpdateHistory(statement: string, elapsed: number, historyResult: { affectedRows?: number; success?: boolean; error?: string } = {}) {
if (!connectionId.value || !tableMeta.value) return;
const connectionName = connectionStore.getConfig(connectionId.value)?.name || "";
const success = historyResult.success ?? true;
await historyStore.add({
connection_id: connectionId.value,
connection_name: connectionName,
database: database.value ?? "",
sql: statement,
execution_time_ms: elapsed,
success,
error: success ? undefined : historyResult.error,
activity_kind: "data_change",
operation: "UPDATE",
target: tableHistoryTarget(),
affected_rows: success ? historyResult.affectedRows : undefined,
details_json: JSON.stringify({
schema: tableMeta.value.schema,
table: tableMeta.value.tableName,
conditional_update: true,
statement_count: 1,
execution_outcome: success ? "completed" : "failed",
error: success ? undefined : historyResult.error,
}),
});
}
function isConditionalUpdateTerminalFailure(error: unknown) {
const backendError = normalizeBackendError(error);
return backendError?.operationOutcome === "not_started" || backendError?.code === "DBX-JDBC-4001" || backendError?.diagnostics?.category === "sql";
}
function reloadCurrentData() {
options.prepareFullReload?.();
options.emit("reload", sql.value, searchText.value, options.currentWhereInput.value, orderByInput.value.trim() || undefined, pageSize.value, (currentPage.value - 1) * pageSize.value);
}
function completeConditionalUpdate(execution: ConditionalUpdateExecution) {
if (conditionalUpdateExecution.value !== execution) return false;
execution.outcome = "completed";
conditionalUpdateExecution.value = undefined;
isSaving.value = false;
reloadCurrentData();
return true;
}
function scheduleConditionalUpdateTerminalCheck(execution: ConditionalUpdateExecution) {
if (execution.terminalCheckScheduled) return;
execution.terminalCheckScheduled = true;
setTimeout(() => {
execution.terminalCheckScheduled = false;
if (conditionalUpdateExecution.value !== execution) return;
void api
.cancelConditionalUpdate(execution.executionId)
.then((cancellation) => {
if (cancellation.terminal) {
completeConditionalUpdate(execution);
} else {
scheduleConditionalUpdateTerminalCheck(execution);
}
})
.catch(() => scheduleConditionalUpdateTerminalCheck(execution));
}, 1_000);
}
async function executeConditionalUpdate(statement: string): Promise<{ affectedRows?: number } | null> {
if (isSaving.value || !connectionId.value || !tableMeta.value) return null;
if (editingCell.value) commitEdit();
if (hasPendingChanges.value) {
saveError.value = i18n.global.t("grid.conditionalBulkEditPendingChanges");
return null;
}
saveError.value = "";
const connection = connectionStore.getConfig(connectionId.value);
const productionAssessment = assessProductionSql(statement, connection, database.value);
if (productionAssessment.active && productionAssessment.isMutation) {
const confirmed = await productionSafetyStore.requestConfirmation({
sql: statement,
connectionName: connection?.name,
database: database.value,
productionDatabases: productionAssessment.databases,
source: "Data editor",
});
if (!confirmed) return null;
}
const execution: ConditionalUpdateExecution = {
executionId: uuid(),
dispatched: false,
cancelRequested: false,
cancelling: false,
terminalCheckScheduled: false,
outcome: "not-started",
};
conditionalUpdateExecution.value = execution;
isSaving.value = true;
const startedAt = Date.now();
try {
if (execution.cancelRequested) return null;
execution.dispatched = true;
execution.outcome = "running";
const result = await api.executeConditionalUpdate(connectionId.value, database.value ?? "", statement, tableMeta.value.schema, execution.executionId);
if (conditionalUpdateExecution.value !== execution) return null;
execution.outcome = "completed";
try {
await recordConditionalUpdateHistory(statement, Date.now() - startedAt, { affectedRows: result.affected_rows });
} catch (historyError) {
console.warn("[DBX] failed to record conditional data grid update history", historyError);
}
reloadCurrentData();
return { affectedRows: result?.affected_rows };
} catch (error) {
if (conditionalUpdateExecution.value !== execution) return null;
const message = normalizeDataGridSaveError(databaseType.value, error);
saveError.value = message;
if (isConditionalUpdateTerminalFailure(error)) {
execution.outcome = "failed";
try {
await recordConditionalUpdateHistory(statement, Date.now() - startedAt, { success: false, error: message });
} catch (historyError) {
console.warn("[DBX] failed to record conditional data grid update history", historyError);
}
reloadCurrentData();
} else {
// A dispatch may reach the database even when the client times out or
// loses its transport. Keep the cancel path alive until the outcome is known.
execution.outcome = normalizeBackendError(error)?.operationOutcome === "not_started" ? "not-started" : "unknown";
}
return null;
} finally {
if (conditionalUpdateExecution.value === execution && execution.outcome !== "unknown") {
conditionalUpdateExecution.value = undefined;
isSaving.value = false;
}
}
}
async function cancelConditionalUpdate(): Promise<boolean> {
const execution = conditionalUpdateExecution.value;
if (!execution || execution.cancelling) return false;
execution.cancelRequested = true;
if (!execution.dispatched) {
execution.outcome = "not-started";
conditionalUpdateExecution.value = undefined;
isSaving.value = false;
return true;
}
execution.cancelling = true;
triggerRef(conditionalUpdateExecution);
try {
const cancellation = await api.cancelConditionalUpdate(execution.executionId);
if (conditionalUpdateExecution.value !== execution) return false;
if (!cancellation.terminal) {
scheduleConditionalUpdateTerminalCheck(execution);
return false;
}
return completeConditionalUpdate(execution);
} catch (error) {
saveError.value = normalizeDataGridSaveError(databaseType.value, error);
return false;
} finally {
execution.cancelling = false;
if (conditionalUpdateExecution.value === execution) triggerRef(conditionalUpdateExecution);
}
}
async function saveChanges(saveOptions: SaveChangesOptions = {}) {
if (isSaving.value) {
if (saveOptions.autoSave) pendingAutoSaveRequested = true;
@@ -1627,6 +1809,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
function discardChanges() {
if (isConditionalUpdateActive.value) return;
dirtyRows.value = new Map();
newRows.value = [];
newRowMeta.value = [];
@@ -1776,6 +1959,8 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
transactionActive,
isSaving,
saveError,
isConditionalUpdateActive,
conditionalUpdateExecution,
useTransaction,
beginBatch,
commitBatch,
@@ -1805,6 +1990,8 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
restoreRows,
deleteSelectedRow,
saveChanges,
executeConditionalUpdate,
cancelConditionalUpdate,
discardChanges,
canUndoPendingChange,
canRedoPendingChange,