fix(mysql): optionally keep explicit transactions in autocommit tabs
This commit is contained in:
35 files changed
+1274
-47
No files matched your search
+196
@@ -0,0 +1,196 @@
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
analyzeEditableQueryEditability: vi.fn(),
|
||||
beginManualTransaction: vi.fn(),
|
||||
closeClientConnectionSession: vi.fn(),
|
||||
closeQuerySession: vi.fn(),
|
||||
commitManualTransaction: vi.fn(),
|
||||
executeInManualTransaction: vi.fn(),
|
||||
executeMulti: vi.fn(),
|
||||
getConnectionConfig: vi.fn(),
|
||||
prepareQueryPaginationExecutionPlan: vi.fn(),
|
||||
rollbackManualTransaction: vi.fn(),
|
||||
saveOpenTabsState: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/backend/api", () => ({
|
||||
analyzeEditableQueryEditability: mocks.analyzeEditableQueryEditability,
|
||||
beginManualTransaction: mocks.beginManualTransaction,
|
||||
closeClientConnectionSession: mocks.closeClientConnectionSession,
|
||||
closeQuerySession: mocks.closeQuerySession,
|
||||
commitManualTransaction: mocks.commitManualTransaction,
|
||||
executeInManualTransaction: mocks.executeInManualTransaction,
|
||||
executeMulti: mocks.executeMulti,
|
||||
prepareQueryPaginationExecutionPlan: mocks.prepareQueryPaginationExecutionPlan,
|
||||
rollbackManualTransaction: mocks.rollbackManualTransaction,
|
||||
saveOpenTabsState: mocks.saveOpenTabsState,
|
||||
}));
|
||||
|
||||
vi.mock("@/stores/connectionStore", () => ({
|
||||
useConnectionStore: () => ({
|
||||
ensureConnected: vi.fn().mockResolvedValue(undefined),
|
||||
getConfig: mocks.getConnectionConfig,
|
||||
recordConnectionLostError: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/stores/settingsStore", () => ({
|
||||
useSettingsStore: () => ({
|
||||
editorSettings: {
|
||||
autoCalculateTotalRows: false,
|
||||
continueOnErrorOnBatch: false,
|
||||
pageSize: 100,
|
||||
queryResultMaxRowsEnabled: false,
|
||||
queryResultMaxRows: 1000,
|
||||
openTabsRestoreMode: "all",
|
||||
confirmUnsavedSqlClose: false,
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
function installLocalStorage() {
|
||||
const data = new Map<string, string>();
|
||||
vi.stubGlobal("localStorage", {
|
||||
getItem: vi.fn((key: string) => data.get(key) ?? null),
|
||||
setItem: vi.fn((key: string, value: string) => data.set(key, value)),
|
||||
removeItem: vi.fn((key: string) => data.delete(key)),
|
||||
});
|
||||
}
|
||||
|
||||
type AutoCommitRolledBackTab = {
|
||||
autoCommitOpenTransaction?: boolean;
|
||||
autoCommitTxnRolledBack?: boolean;
|
||||
autoCommitSessionTxnRolledBack?: boolean;
|
||||
autoCommitSessionTxnRolledBackNotified?: boolean;
|
||||
};
|
||||
|
||||
function emptyTab(): AutoCommitRolledBackTab {
|
||||
return {};
|
||||
}
|
||||
|
||||
describe("applyAutoCommitTransactionReport", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
installLocalStorage();
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("mirrors the open-transaction marker the backend reported", async () => {
|
||||
const { applyAutoCommitTransactionReport } = await import("@/stores/queryStore");
|
||||
const tab = emptyTab();
|
||||
applyAutoCommitTransactionReport(tab as never, [{ auto_commit_open_transaction: true }] as never);
|
||||
expect(tab.autoCommitOpenTransaction).toBe(true);
|
||||
applyAutoCommitTransactionReport(tab as never, [{ auto_commit_open_transaction: false }] as never);
|
||||
expect(tab.autoCommitOpenTransaction).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps reporting an explicitly opened transaction that was rolled back", async () => {
|
||||
const { applyAutoCommitTransactionReport } = await import("@/stores/queryStore");
|
||||
const tab = emptyTab();
|
||||
applyAutoCommitTransactionReport(tab as never, [{ auto_commit_explicit_transaction_rolled_back: true }] as never);
|
||||
expect(tab.autoCommitTxnRolledBack).toBe(true);
|
||||
|
||||
// The user dismisses the notice; the next execution that rolls back another
|
||||
// explicit transaction must raise it again — the tab lost real work.
|
||||
tab.autoCommitTxnRolledBack = false;
|
||||
applyAutoCommitTransactionReport(tab as never, [{ auto_commit_explicit_transaction_rolled_back: true }] as never);
|
||||
expect(tab.autoCommitTxnRolledBack).toBe(true);
|
||||
});
|
||||
|
||||
it("reports a session-level implicit rollback once per connection", async () => {
|
||||
const { applyAutoCommitTransactionReport } = await import("@/stores/queryStore");
|
||||
const tab = emptyTab();
|
||||
applyAutoCommitTransactionReport(tab as never, [{ auto_commit_session_autocommit_rolled_back: true }] as never);
|
||||
expect(tab.autoCommitSessionTxnRolledBack).toBe(true);
|
||||
expect(tab.autoCommitTxnRolledBack).toBeUndefined();
|
||||
|
||||
// `SET autocommit = 0` rolls back an implicit transaction after *every*
|
||||
// execution; dismissing the notice must not bring it straight back.
|
||||
tab.autoCommitSessionTxnRolledBack = false;
|
||||
applyAutoCommitTransactionReport(tab as never, [{ auto_commit_session_autocommit_rolled_back: true }] as never);
|
||||
expect(tab.autoCommitSessionTxnRolledBack).toBe(false);
|
||||
|
||||
// Auto-commit is back on (or the execution never used the tab connection):
|
||||
// the next auto-commit-off session is reported again.
|
||||
applyAutoCommitTransactionReport(tab as never, [{ auto_commit_open_transaction: false }] as never);
|
||||
applyAutoCommitTransactionReport(tab as never, [{ auto_commit_session_autocommit_rolled_back: true }] as never);
|
||||
expect(tab.autoCommitSessionTxnRolledBack).toBe(true);
|
||||
});
|
||||
|
||||
it("prefers the explicit notice when a batch carries both markers", async () => {
|
||||
const { applyAutoCommitTransactionReport } = await import("@/stores/queryStore");
|
||||
const tab = emptyTab();
|
||||
applyAutoCommitTransactionReport(tab as never, [{ auto_commit_explicit_transaction_rolled_back: true, auto_commit_session_autocommit_rolled_back: true }] as never);
|
||||
expect(tab.autoCommitTxnRolledBack).toBe(true);
|
||||
expect(tab.autoCommitSessionTxnRolledBack).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("auto-commit tab transaction actions", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
installLocalStorage();
|
||||
setActivePinia(createPinia());
|
||||
mocks.getConnectionConfig.mockReturnValue({
|
||||
id: "mysql-1",
|
||||
name: "MySQL",
|
||||
db_type: "mysql",
|
||||
database: "dbx",
|
||||
query_timeout_secs: 30,
|
||||
});
|
||||
mocks.prepareQueryPaginationExecutionPlan.mockImplementation(async (options) => ({
|
||||
sqlToExecute: options.sql,
|
||||
pageSql: undefined,
|
||||
pageLimit: undefined,
|
||||
pageOffset: undefined,
|
||||
countSql: undefined,
|
||||
useAgentResultSession: false,
|
||||
}));
|
||||
mocks.analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "not-select" });
|
||||
mocks.saveOpenTabsState.mockResolvedValue(undefined);
|
||||
mocks.executeMulti.mockResolvedValue({
|
||||
results: [{ columns: [], rows: [], affected_rows: 1, execution_time_ms: 1, auto_commit_open_transaction: false }],
|
||||
});
|
||||
});
|
||||
|
||||
async function setupAutoCommitTabWithKeptTransaction() {
|
||||
const { useQueryStore } = await import("@/stores/queryStore");
|
||||
const store = useQueryStore();
|
||||
const tabId = store.createTab("mysql-1", "dbx", "Query", "query");
|
||||
const tab = store.tabs.find((item) => item.id === tabId);
|
||||
if (!tab) throw new Error("tab missing");
|
||||
// The backend reported a kept explicit transaction on this tab connection.
|
||||
tab.autoCommitOpenTransaction = true;
|
||||
tab.autoCommitSessionTxnRolledBack = true;
|
||||
tab.autoCommitSessionTxnRolledBackNotified = true;
|
||||
return { store, tabId, tab };
|
||||
}
|
||||
|
||||
it("commits a kept auto-commit transaction as an ordinary statement", async () => {
|
||||
const { store, tabId } = await setupAutoCommitTabWithKeptTransaction();
|
||||
await store.commitTransaction(tabId);
|
||||
|
||||
expect(mocks.executeMulti).toHaveBeenCalledOnce();
|
||||
expect(mocks.executeMulti.mock.calls[0][2]).toBe("COMMIT");
|
||||
});
|
||||
|
||||
it("rolls back a kept auto-commit transaction as an ordinary statement", async () => {
|
||||
const { store, tabId } = await setupAutoCommitTabWithKeptTransaction();
|
||||
await store.rollbackTransaction(tabId);
|
||||
|
||||
expect(mocks.executeMulti).toHaveBeenCalledOnce();
|
||||
expect(mocks.executeMulti.mock.calls[0][2]).toBe("ROLLBACK");
|
||||
});
|
||||
|
||||
it("drops the session-level notice when the tab switches connection", async () => {
|
||||
const { store, tabId, tab } = await setupAutoCommitTabWithKeptTransaction();
|
||||
store.updateConnection(tabId, "mysql-2", "dbx");
|
||||
|
||||
expect(tab.autoCommitSessionTxnRolledBack).toBeUndefined();
|
||||
expect(tab.autoCommitSessionTxnRolledBackNotified).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -904,6 +904,39 @@ function getI18nT() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Mirrors the MySQL auto-commit settlement the backend reported for this
|
||||
* execution onto the tab. Absent markers (non-MySQL connections, executions
|
||||
* that never touched a tab connection) leave the previous state untouched.
|
||||
*
|
||||
* The two rollback notices are deliberately different: a `BEGIN` the user
|
||||
* typed is reported on every execution (the tab just lost real work), while a
|
||||
* session sitting on `SET autocommit = 0` has an implicit transaction rolled
|
||||
* back after *every* execution — that one is raised once per connection and
|
||||
* re-armed only after the connection stops reporting it, so dismissing it
|
||||
* does not bring it back on the next keystroke batch. */
|
||||
export function applyAutoCommitTransactionReport(tab: QueryTab, results: QueryResult[]) {
|
||||
const openTransaction = results.find((result) => result.auto_commit_open_transaction !== undefined)?.auto_commit_open_transaction;
|
||||
if (openTransaction !== undefined) tab.autoCommitOpenTransaction = openTransaction;
|
||||
const explicitRolledBack = results.some((result) => result.auto_commit_explicit_transaction_rolled_back === true);
|
||||
const sessionRolledBack = results.some((result) => result.auto_commit_session_autocommit_rolled_back === true);
|
||||
if (explicitRolledBack) {
|
||||
tab.autoCommitTxnRolledBack = true;
|
||||
tab.autoCommitSessionTxnRolledBackNotified = false;
|
||||
return;
|
||||
}
|
||||
if (sessionRolledBack) {
|
||||
if (!tab.autoCommitSessionTxnRolledBackNotified) {
|
||||
tab.autoCommitSessionTxnRolledBack = true;
|
||||
tab.autoCommitSessionTxnRolledBackNotified = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// This execution rolled nothing back: the auto-commit-off session may be gone
|
||||
// (or the execution never used the tab connection), so re-arm the notice for
|
||||
// the next time it happens.
|
||||
tab.autoCommitSessionTxnRolledBackNotified = false;
|
||||
}
|
||||
|
||||
export const useQueryStore = defineStore("query", () => {
|
||||
const redisMonitors = new Map<string, () => void>();
|
||||
const t = getI18nT();
|
||||
@@ -4881,6 +4914,16 @@ export const useQueryStore = defineStore("query", () => {
|
||||
if (tab.txnPossiblyDirty !== undefined) tab.txnPossiblyDirty = false;
|
||||
}
|
||||
|
||||
/** Auto-commit tabs mirror the backend's report of an open explicit
|
||||
* transaction. The flag is dropped whenever the tab stops pointing at the
|
||||
* connection that reported it (target switch, tab close), so a stale badge
|
||||
* can never outlive the session it describes. */
|
||||
function clearAutoCommitOpenTransaction(tab: { autoCommitOpenTransaction?: boolean; autoCommitSessionTxnRolledBack?: boolean; autoCommitSessionTxnRolledBackNotified?: boolean }) {
|
||||
if (tab.autoCommitOpenTransaction !== undefined) tab.autoCommitOpenTransaction = false;
|
||||
tab.autoCommitSessionTxnRolledBack = undefined;
|
||||
tab.autoCommitSessionTxnRolledBackNotified = undefined;
|
||||
}
|
||||
|
||||
/** Centralized manual-session cleanup. Clears every field tied to a manual
|
||||
* transaction session exactly when that session is conclusively ended or
|
||||
* discarded. Callers must not assign these fields individually. */
|
||||
@@ -4903,11 +4946,19 @@ export const useQueryStore = defineStore("query", () => {
|
||||
}
|
||||
clearTxnPossiblyDirty(tab);
|
||||
tab.txnAutoRolledBack = false;
|
||||
clearAutoCommitOpenTransaction(tab);
|
||||
}
|
||||
|
||||
async function commitTransaction(id: string) {
|
||||
const tab = tabs.value.find((t) => t.id === id);
|
||||
if (!tab?.txnSessionId) return;
|
||||
if (!tab) return;
|
||||
if (!tab.txnSessionId) {
|
||||
// Auto-commit tab (`Tx:A`) that keeps explicit user transactions: the
|
||||
// transaction lives on the tab's own connection, so COMMIT is an ordinary
|
||||
// statement on that connection.
|
||||
if (tab.autoCommitOpenTransaction) await executeCurrentSql("COMMIT", { tabId: tab.id });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await api.commitManualTransaction(tab.txnSessionId);
|
||||
} finally {
|
||||
@@ -4917,7 +4968,11 @@ export const useQueryStore = defineStore("query", () => {
|
||||
|
||||
async function rollbackTransaction(id: string) {
|
||||
const tab = tabs.value.find((t) => t.id === id);
|
||||
if (!tab?.txnSessionId) return;
|
||||
if (!tab) return;
|
||||
if (!tab.txnSessionId) {
|
||||
if (tab.autoCommitOpenTransaction) await executeCurrentSql("ROLLBACK", { tabId: tab.id });
|
||||
return;
|
||||
}
|
||||
const sessionId = tab.txnSessionId;
|
||||
// Remove the old session before the backend responds: a target switch may
|
||||
// start a new transaction while this rollback is still in flight.
|
||||
@@ -7343,6 +7398,8 @@ export const useQueryStore = defineStore("query", () => {
|
||||
timeoutSecs: queryTimeoutSecs,
|
||||
catalog: executionCatalog,
|
||||
continueOnError: continueOnBatchError,
|
||||
// MySQL-family connections only use this; other drivers ignore it.
|
||||
...(settingsStore.editorSettings.keepExplicitTransactionInAutoCommit ? { preserveExplicitTransaction: true } : {}),
|
||||
};
|
||||
queryExecutionLog("info", "execute-multi:invoke", {
|
||||
traceId,
|
||||
@@ -7527,6 +7584,7 @@ export const useQueryStore = defineStore("query", () => {
|
||||
console.warn("[DBX] Failed to resolve SAP HANA CURRENT_SCHEMA", error);
|
||||
}
|
||||
}
|
||||
if (tab.autoCommit !== false) applyAutoCommitTransactionReport(tab, results);
|
||||
const current = findExecutionTab(id);
|
||||
if (current?.executionId === executionId && manualTransactionTargetEpoch(current) === executionTargetEpoch) {
|
||||
if (captureResultRun && current.isCancelling && restorePendingResultRun(current, executionId)) return false;
|
||||
|
||||
@@ -945,6 +945,12 @@ export interface EditorSettings {
|
||||
clickTableNavigationTarget: ClickTableNavigationTarget;
|
||||
completionTriggerMode: SqlCompletionTriggerMode;
|
||||
defaultTransactionMode: DefaultTransactionMode;
|
||||
/** Auto-commit (`Tx:A`) tabs with a MySQL-family connection: keep a
|
||||
* transaction the user opens explicitly (`BEGIN` / `START TRANSACTION`) open
|
||||
* across executions until COMMIT / ROLLBACK instead of rolling it back when
|
||||
* each execution ends. Off by default: the rollback is what stops a leftover
|
||||
* transaction from pinning the tab's read snapshot (#9479). */
|
||||
keepExplicitTransactionInAutoCommit: boolean;
|
||||
}
|
||||
|
||||
export interface ToolbarItems {
|
||||
@@ -1202,6 +1208,7 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {
|
||||
clickTableNavigationTarget: "data",
|
||||
completionTriggerMode: "positional",
|
||||
defaultTransactionMode: "auto",
|
||||
keepExplicitTransactionInAutoCommit: false,
|
||||
};
|
||||
|
||||
export const STORAGE_KEY = "dbx-editor-settings";
|
||||
@@ -1790,6 +1797,7 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
|
||||
clickTableNavigationTarget: normalizeClickTableNavigationTarget(settings.clickTableNavigationTarget),
|
||||
completionTriggerMode: normalizeCompletionTriggerMode(settings.completionTriggerMode),
|
||||
defaultTransactionMode: normalizeDefaultTransactionMode(settings.defaultTransactionMode),
|
||||
keepExplicitTransactionInAutoCommit: settings.keepExplicitTransactionInAutoCommit === true,
|
||||
backgroundImage: normalizeBackgroundImageSettings(settings.backgroundImage),
|
||||
};
|
||||
}
|
||||
@@ -2542,6 +2550,7 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
if (partial.clickTableNavigationTarget !== undefined) editorSettings.value.clickTableNavigationTarget = normalizeClickTableNavigationTarget(partial.clickTableNavigationTarget);
|
||||
if (partial.completionTriggerMode !== undefined) editorSettings.value.completionTriggerMode = normalizeCompletionTriggerMode(partial.completionTriggerMode);
|
||||
if (partial.defaultTransactionMode !== undefined) editorSettings.value.defaultTransactionMode = normalizeDefaultTransactionMode(partial.defaultTransactionMode);
|
||||
if (partial.keepExplicitTransactionInAutoCommit !== undefined) editorSettings.value.keepExplicitTransactionInAutoCommit = partial.keepExplicitTransactionInAutoCommit === true;
|
||||
if (partial.flatteningMultiLineText !== undefined) editorSettings.value.flatteningMultiLineText = partial.flatteningMultiLineText;
|
||||
if (partial.dataGridShowWhitespace !== undefined) editorSettings.value.dataGridShowWhitespace = partial.dataGridShowWhitespace;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user