Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: auto-saving worksheet (#18911)
ecmadao39f6a89c277e
diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vueindex c47d1246cc..95f2cba606 100644--- a/frontend/src/components/ProvideSQLEditorContext.vue+++ b/frontend/src/components/ProvideSQLEditorContext.vue@@ -91,7 +91,7 @@ const {useRouteChangeGuard(computed(() => {return (- tabStore.openTabList.find((tab) => tab.status === "DIRTY") !== undefined+ tabStore.openTabList.find((tab) => tab.status !== "CLEAN") !== undefined);}),`${t("sql-editor.tab.unsaved-worksheet")} ${t("common.leave-without-saving")}`diff --git a/frontend/src/store/modules/v1/worksheet.ts b/frontend/src/store/modules/v1/worksheet.tsindex b00543543c..04bf829a67 100644--- a/frontend/src/store/modules/v1/worksheet.ts+++ b/frontend/src/store/modules/v1/worksheet.ts@@ -205,14 +205,20 @@ export const useWorkSheetStore = defineStore("worksheet_v1", () => {return response.worksheets;};- const patchWorksheet = async (worksheet: Worksheet, updateMask: string[]) => {+ const patchWorksheet = async (+ worksheet: Worksheet,+ updateMask: string[],+ signal?: AbortSignal+ ) => {if (!worksheet.name) return;const request = create(UpdateWorksheetRequestSchema, {worksheet: worksheet,updateMask: { paths: updateMask },});- const response =- await worksheetServiceClientConnect.updateWorksheet(request);+ const response = await worksheetServiceClientConnect.updateWorksheet(+ request,+ { signal }+ );setCacheEntry(response, "FULL");return response;};diff --git a/frontend/src/types/sqlEditor/tab.ts b/frontend/src/types/sqlEditor/tab.tsindex da75ce1c32..83b1e310e3 100644--- a/frontend/src/types/sqlEditor/tab.ts+++ b/frontend/src/types/sqlEditor/tab.ts@@ -7,6 +7,7 @@ import type { EditorPanelViewState } from "./tabViewState";export type SQLEditorTabStatus =| "DIRTY" // edited+ | "SAVING" // auto-saving in progress| "CLEAN"; // saved to a remote sheetexport type SQLEditorTabMode = "WORKSHEET" | "ADMIN";diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vueindex b898ae967f..722aaf43b0 100644--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue@@ -270,6 +270,8 @@ const allowSave = computed(() => {return true;}}+ // Only disable when status is CLEAN (nothing to save)+ // SAVING is allowed - manual save will abort auto-save and proceedif (tab.status === "CLEAN") {return false;}@@ -280,7 +282,7 @@ const allowSave = computed(() => {const allowShare = computed(() => {const tab = currentTab.value;if (!tab) return false;- if (tab.status === "DIRTY") return false;+ if (tab.status !== "CLEAN") return false;if (isEmptyStatement.value) return false;if (isDisconnected.value) return false;if (tab.worksheet) {diff --git a/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vue b/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vueindex 36db771ffc..dfa906a28e 100644--- a/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vue+++ b/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vue@@ -46,6 +46,7 @@ import { useSQLEditorContext } from "../context";const worksheetV1Store = useWorkSheetStore();const editorContext = useSQLEditorContext();+const { abortAutoSave } = editorContext;const { getPwdForWorksheet } = useSheetContextByView("my");const folderFormRef = ref<InstanceType<typeof FolderForm>>();@@ -67,6 +68,9 @@ const doSaveSheet = async () => {return;}+ // Abort any in-progress auto-save - manual save takes priority+ abortAutoSave();+const {worksheet,connection,diff --git a/frontend/src/views/sql-editor/TabList/TabItem/Suffix.vue b/frontend/src/views/sql-editor/TabList/TabItem/Suffix.vueindex f97040eaa3..7dbda973a9 100644--- a/frontend/src/views/sql-editor/TabList/TabItem/Suffix.vue+++ b/frontend/src/views/sql-editor/TabList/TabItem/Suffix.vue@@ -11,7 +11,11 @@@mouseenter="state.hovering = true"@mouseleave="state.hovering = false">- <carbon:dot-mark v-if="icon === 'unsaved'" class="icon unsaved" />+ <LoaderCircleIcon+ v-if="icon === 'saving'"+ class="icon saving animate-spin"+ />+ <carbon:dot-mark v-else-if="icon === 'unsaved'" class="icon unsaved" /><heroicons-solid:xv-else-if="icon === 'close'"class="icon close"@@ -22,6 +26,7 @@</template><script lang="ts" setup>+import { LoaderCircleIcon } from "lucide-vue-next";import { computed, reactive } from "vue";import type { SQLEditorTab } from "@/types";@@ -29,7 +34,7 @@ type LocalState = {hovering: boolean;};-type IconType = "unsaved" | "close";+type IconType = "unsaved" | "saving" | "close";const props = defineProps<{tab: SQLEditorTab;@@ -44,10 +49,14 @@ defineEmits<{}>();const icon = computed((): IconType | undefined => {+ const { mode, status } = props.tab;+ // Always show saving indicator when saving, even when hovering+ if (mode === "WORKSHEET" && status === "SAVING") {+ return "saving";+ }if (state.hovering) {return "close";}- const { mode, status } = props.tab;if (mode === "WORKSHEET" && status === "DIRTY") {return "unsaved";}@@ -72,7 +81,10 @@ const icon = computed((): IconType | undefined => {.suffix.closable {cursor: pointer;}-.suffix.closable.dirty .icon {+.suffix.closable.DIRTY .icon {+ color: rgb(var(--color-accent));+}+.suffix.closable.SAVING .icon.saving {color: rgb(var(--color-accent));}.suffix.closable .icon:hover {diff --git a/frontend/src/views/sql-editor/TabList/TabList.vue b/frontend/src/views/sql-editor/TabList/TabList.vueindex 4177189b88..c90ba5b447 100644--- a/frontend/src/views/sql-editor/TabList/TabList.vue+++ b/frontend/src/views/sql-editor/TabList/TabList.vue@@ -136,7 +136,7 @@ const handleAddTab = async () => {const handleRemoveTab = async (tab: SQLEditorTab, focusWhenConfirm = false) => {const _defer = defer<boolean>();- if (tab.mode === "WORKSHEET" && tab.status === "DIRTY") {+ if (tab.mode === "WORKSHEET" && tab.status !== "CLEAN") {if (focusWhenConfirm) {tabStore.setCurrentTabId(tab.id);}diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.tsindex 77cf4cf49a..8065b87dee 100644--- a/frontend/src/views/sql-editor/context.ts+++ b/frontend/src/views/sql-editor/context.ts@@ -1,11 +1,13 @@import { create } from "@bufbuild/protobuf";-import { useLocalStorage } from "@vueuse/core";+import { useLocalStorage, watchDebounced } from "@vueuse/core";import Emittery from "emittery";import { isUndefined } from "lodash-es";import { type IRange } from "monaco-editor";+import { storeToRefs } from "pinia";import type { ComputedRef, InjectionKey, Ref } from "vue";import { computed, inject, nextTick, provide, ref } from "vue";import {+ pushNotification,useProjectIamPolicyStore,useProjectV1Store,useSQLEditorStore,@@ -22,6 +24,7 @@ import {import {extractWorksheetConnection,isSimilarDefaultSQLEditorTabTitle,+ isWorksheetWritableV1,NEW_WORKSHEET_TITLE,suggestedTabTitleForSQLEditorConnection,} from "@/utils";@@ -92,7 +95,10 @@ export type SQLEditorContext = {database: string;statement: string;folders?: string[];+ signal?: AbortSignal;}) => Promise<SQLEditorTab | undefined>;+ // Abort any in-progress auto-save (used when manual save takes priority)+ abortAutoSave: () => void;};export const KEY = Symbol(@@ -138,6 +144,7 @@ export const provideSQLEditorContext = () => {database,statement,folders,+ signal,}: {tabId: string;worksheet?: string;@@ -145,6 +152,7 @@ export const provideSQLEditorContext = () => {database: string;statement: string;folders?: string[];+ signal?: AbortSignal;}) => {const connection = await extractWorksheetConnection({ database });let worksheetTitle = title ?? "";@@ -168,9 +176,13 @@ export const provideSQLEditorContext = () => {database,content: new TextEncoder().encode(statement),},- ["title", "database", "content"]+ ["title", "database", "content"],+ signal);- if (updated && !isUndefined(folders)) {+ if (!updated) {+ return;+ }+ if (!isUndefined(folders)) {await worksheetStore.upsertWorksheetOrganizer({worksheet: updated.name,@@ -269,6 +281,16 @@ export const provideSQLEditorContext = () => {}};+ // Auto-save abort controller - allows manual save to cancel in-progress auto-save+ let autoSaveController: AbortController | null = null;++ const abortAutoSave = () => {+ if (autoSaveController) {+ autoSaveController.abort();+ autoSaveController = null;+ }+ };+const context: SQLEditorContext = {asidePanelTab: ref("WORKSHEET"),showConnectionPanel,@@ -287,8 +309,137 @@ export const provideSQLEditorContext = () => {},createWorksheet,maybeUpdateWorksheet,+ abortAutoSave,};+ // Auto-saving for current tab.+ // This handles several complex scenarios:+ //+ // Scenario 1: Normal auto-save+ // 1. User types "statement1", status → DIRTY+ // 2. After 2s debounce, auto-save starts, status → SAVING+ // 3. Auto-save completes, status → CLEAN+ //+ // Scenario 2: User types during auto-save+ // 1. User types "statement1", status → DIRTY+ // 2. Auto-save #1 starts for "statement1", status → SAVING+ // 3. User types more → "statement1 statement2", status → DIRTY+ // 4. Auto-save #1 completes, status → CLEAN+ // 5. Finally block: statement changed, status → DIRTY+ // 6. After 2s debounce, auto-save #2 starts for "statement1 statement2"+ //+ // Scenario 3: Manual save during auto-save+ // 1. User types "statement1", status → DIRTY+ // 2. Auto-save #1 starts, status → SAVING+ // 3. User clicks save → abortAutoSave() called+ // 4. Auto-save #1 aborted (throws AbortError), wasAborted = true+ // 5. Manual save runs and completes, status → CLEAN+ // 6. Auto-save #1's finally: wasAborted = true, skips logic+ //+ // Scenario 4: Rapid typing (newer auto-save aborts older)+ // 1. User types "statement1", status → DIRTY+ // 2. Auto-save #1 starts (slow network), status → SAVING+ // 3. User types "statement1 statement2", status → DIRTY+ // 4. After 2s debounce, abortAutoSave() aborts #1, auto-save #2 starts+ // 5. Auto-save #1's finally: wasAborted = true, skips logic+ // 6. Auto-save #2 completes with correct content+ //+ // Scenario 5: Auto-save fails (network/server error)+ // 1. User types "statement1", status → DIRTY+ // 2. Auto-save starts, status → SAVING+ // 3. Network error occurs+ // 4. Catch block: status → DIRTY, error notification shown+ // 5. User can manually save or wait for next auto-save attempt+ //+ // Scenario 6: Tab closed during auto-save+ // 1. User types "statement1", status → DIRTY+ // 2. Auto-save starts, status → SAVING+ // 3. User closes tab (warning shown since status !== CLEAN)+ // 4. User confirms, tab removed from store+ // 5. Auto-save completes, finally block runs+ // 6. getTabById returns undefined, updateTab is no-op (safe)+ //+ // Guard conditions (auto-save skipped):+ // - No worksheet (draft tab): user must manually save to create worksheet+ // - Read-only worksheet: user doesn't have write permission+ // - Status is CLEAN: nothing to save+ //+ const { currentTab } = storeToRefs(tabStore);++ watchDebounced(+ () => currentTab.value?.statement,+ async () => {+ const tab = currentTab.value;+ if (!tab || !tab.worksheet || tab.status === "CLEAN") {+ return;+ }++ // Check write permission+ const worksheet = worksheetStore.getWorksheetByName(tab.worksheet);+ if (!worksheet || !isWorksheetWritableV1(worksheet)) {+ return;+ }++ // Abort any in-progress auto-save before starting a new one+ abortAutoSave();++ // Capture the statement and tab id before async operation+ const statementToSave = tab.statement;+ const tabId = tab.id;++ // Create new abort controller for this auto-save+ autoSaveController = new AbortController();+ // Set status to SAVING+ tabStore.updateTab(tabId, { status: "SAVING" });++ // Track if this auto-save was aborted+ let wasAborted = false;++ try {+ // the maybeUpdateWorksheet will set status to CLEAN+ await maybeUpdateWorksheet({+ tabId,+ worksheet: tab.worksheet,+ database: tab.connection.database,+ statement: statementToSave,+ signal: autoSaveController.signal,+ });+ } catch (error) {+ // Don't handle aborted requests - a newer save or manual save took priority+ if (error instanceof Error && error.name === "AbortError") {+ wasAborted = true;+ return;+ }+ // Only revert to DIRTY if still in SAVING state+ // (user might have manually saved successfully during this time)+ if (tabStore.getTabById(tabId)?.status === "SAVING") {+ tabStore.updateTab(tabId, { status: "DIRTY" });+ }+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "Auto-save failed",+ description: error instanceof Error ? error.message : "Unknown error",+ });+ } finally {+ autoSaveController = null;++ // Skip for aborted requests - manual save or newer auto-save took priority+ if (wasAborted) {+ return;+ }++ // After save, check if the statement changed while we were saving+ // If it did, the user typed more content, so keep status as DIRTY+ const currentStatement = tabStore.getTabById(tabId)?.statement;+ if (currentStatement !== statementToSave) {+ tabStore.updateTab(tabId, { status: "DIRTY" });+ }+ }+ },+ { debounce: 2000 /* 2 seconds */ }+ );+provide(KEY, context);return context;