Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: sql editor tab (#18267)
ecmadao07482720beeb
diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vueindex a8056ae58d..bfad7d8434 100644--- a/frontend/src/components/ProvideSQLEditorContext.vue+++ b/frontend/src/components/ProvideSQLEditorContext.vue@@ -56,6 +56,7 @@ import {emptySQLEditorConnection,extractInstanceResourceName,extractProjectResourceName,+ extractWorksheetConnection,extractWorksheetUID,getDefaultPagination,getSheetStatement,@@ -69,7 +70,6 @@ import {type AsidePanelTab,useSQLEditorContext,} from "@/views/sql-editor/context";-import { extractWorksheetConnection } from "@/views/sql-editor/Sheet";const { t } = useI18n();const route = useRoute();@@ -258,7 +258,7 @@ const prepareConnectionParams = async () => {(tab) => tab.connection.database === database.name);for (const tab of tabs) {- tabStore.removeTab(tab);+ tabStore.closeTab(tab);}return false;}@@ -432,6 +432,7 @@ onMounted(async () => {initializeProject(),]);+ await tabStore.maybeInitProject();await initializeConnectionFromQuery();syncURLWithConnection();});@@ -443,7 +444,6 @@ useEmitteryEventListener(if (!project) {return;}- tabStore.maybeInitProject(project);nextTick(() => {restoreLastVisitedSidebarTab();});diff --git a/frontend/src/store/modules/sqlEditor/extendedTab.ts b/frontend/src/store/modules/sqlEditor/extendedTab.tsdeleted file mode 100644index 5471cd692d..0000000000--- a/frontend/src/store/modules/sqlEditor/extendedTab.ts+++ /dev/null@@ -1,140 +0,0 @@-import { pick } from "lodash-es";-import { defineStore, storeToRefs } from "pinia";-import PouchDB from "pouchdb";-import PouchDBFind from "pouchdb-find";-import { computed } from "vue";-import type { SQLEditorTab } from "@/types";-import { useCurrentUserV1 } from "../v1/auth";-import { extractUserId } from "../v1/common";-import { useSQLEditorStore } from "./editor";--export const EXTENDED_TAB_FIELDS = [- "statement",- "batchQueryContext",- "treeState",-] as const;-export type ExtendedTab = Pick<- SQLEditorTab,- (typeof EXTENDED_TAB_FIELDS)[number]->;-export type ExtendedTabEntity = ExtendedTab & {- _id: string;- _rev?: string;- project: string; // for tracing- user: string; // for tracing-};--PouchDB.plugin(PouchDBFind);--export const useExtendedTabStore = defineStore("sqlEditorExtendedTab", () => {- // context- const { project } = storeToRefs(useSQLEditorStore());- const me = useCurrentUserV1();- const userUID = computed(() => extractUserId(me.value.name));-- // stores- const extendedTabDB = new PouchDB<ExtendedTabEntity>(- "bb.sql-editor.extended-tab",- {- // Remove unused and old data automatically.- auto_compaction: true,- // Do not save and track old revisions, this is for saving storage usage.- revs_limit: 1,- }- );- const ready = Promise.all([- extendedTabDB.createIndex({- index: { name: "idx_tab_user", fields: ["user"] },- }),- extendedTabDB.createIndex({- index: { name: "idx_tab_project", fields: ["project"] },- }),- ]);-- const fetchExtendedTab = async (tab: SQLEditorTab, fallback?: () => void) => {- try {- await ready;- const doc = await extendedTabDB.get(tab.id);- Object.assign(tab, {- _rev: doc._rev,- _user: doc.user,- _project: doc.project,- ...pick(doc, EXTENDED_TAB_FIELDS),- });- } catch (err) {- if (fallback) {- fallback();- }-- if ((err as any)?.status === 404) return;- console.debug("[SQLEditorExtendedTabStore] fetchExtendedTab", err);- }- };-- const saveExtendedTab = async (tab: SQLEditorTab, extended: ExtendedTab) => {- const rev = (tab as any)._rev as string | undefined;- const doc: ExtendedTabEntity = {- _id: tab.id,- project: (tab as any)._project ?? project.value,- user: (tab as any)._user ?? userUID.value,- ...extended,- };- if (rev) {- doc._rev = rev;- }- try {- await ready;- const saved = await extendedTabDB.put(doc, { force: true });- (tab as any)._rev = saved.rev;- } catch (err) {- // We only keep ONE revision for each tab so we could ignore conflict error- if ((err as any)?.name === "conflict") return;- console.warn("[SQLEditorExtendedTabStore] saveExtendedTab", err);- }- };-- const deleteExtendedTab = async (tab: SQLEditorTab) => {- try {- await ready;- const doc = await extendedTabDB.get(tab.id);- await extendedTabDB.remove(doc);- } catch (err) {- console.warn("[SQLEditorExtendedTabStore] deleteExtendedTab", err);- }- };-- const cleanupExtendedTabs = async (- user: string,- validTabIdList: string[]- ) => {- try {- await ready;- const response = await extendedTabDB.find({- selector: {- user: { $eq: user },- _id: { $nin: validTabIdList },- },- });- const docs = response.docs;- if (docs.length === 0) {- return;- }- docs.forEach((doc) => {- (doc as any)._deleted = true;- });- console.debug(- "[SQLEditorExtendedTabStore] cleanupExtendedTabs",- `delete ${docs.length} tabs`- );- await extendedTabDB.bulkDocs(docs);- } catch (err) {- console.warn("[SQLEditorExtendedTabStore] cleanupExtendedTabs", err);- }- };- return {- fetchExtendedTab,- saveExtendedTab,- deleteExtendedTab,- cleanupExtendedTabs,- };-});diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/store/modules/sqlEditor/tab.tsindex 5de2907887..085ba803ab 100644--- a/frontend/src/store/modules/sqlEditor/tab.ts+++ b/frontend/src/store/modules/sqlEditor/tab.ts@@ -1,8 +1,7 @@import type { MaybeRef } from "@vueuse/core";-import { watchThrottled } from "@vueuse/core";-import { head, omit, pick } from "lodash-es";+import { head, pick } from "lodash-es";import { defineStore, storeToRefs } from "pinia";-import { computed, nextTick, reactive, ref, unref, watch } from "vue";+import { computed, reactive, unref, watch } from "vue";import type {BatchQueryContext,CoreSQLEditorTab,@@ -10,16 +9,17 @@ import type {SQLEditorDatabaseQueryContext,SQLEditorTab,} from "@/types";-import { DEFAULT_SQL_EDITOR_TAB_MODE, isValidDatabaseName } from "@/types";+import { isValidDatabaseName } from "@/types";import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import {defaultSQLEditorTab,emptySQLEditorConnection,+ extractWorksheetConnection,+ getSheetStatement,isDisconnectedSQLEditorTab,isSimilarSQLEditorTab,useDynamicLocalStorage,- WebStorageHelper,} from "@/utils";import {extractUserId,@@ -27,168 +27,117 @@ import {useDatabaseV1ByName,useDatabaseV1Store,useEnvironmentV1Store,+ useWorkSheetStore,} from "../v1";import { useCurrentUserV1 } from "../v1/auth";import { useSQLEditorStore } from "./editor";-import {- EXTENDED_TAB_FIELDS,- type ExtendedTab,- useExtendedTabStore,-} from "./extendedTab";import { useWebTerminalStore } from "./webTerminal";-const LOCAL_STORAGE_KEY_PREFIX = "bb.sql-editor-tab";--// Only store the core fields of a tab.-// Don't store anything which might be too large.const PERSISTENT_TAB_FIELDS = ["id",- "title",- "connection",- "mode","worksheet",- "status",+ "mode",+ "batchQueryContext",+ "treeState",] as const;type PersistentTab = Pick<SQLEditorTab, (typeof PERSISTENT_TAB_FIELDS)[number]>;-// `tabsById` stores all PersistentTab items across all projects-const tabsById = reactive(new Map<string, SQLEditorTab>());+const LOCAL_STORAGE_KEY_PREFIX = "bb.sql-editor-tab";export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {// re-expose selected project in sqlEditorStore for shortcutconst { project } = storeToRefs(useSQLEditorStore());-- // states- const { fetchExtendedTab, saveExtendedTab, deleteExtendedTab } =- useExtendedTabStore();+ const tabsById = reactive(new Map<string, SQLEditorTab>());+ const worksheetStore = useWorkSheetStore();const me = useCurrentUserV1();const userUID = computed(() => extractUserId(me.value.name));const keyNamespace = computed(- () => `${LOCAL_STORAGE_KEY_PREFIX}.${userUID.value}`+ () => `${LOCAL_STORAGE_KEY_PREFIX}.${project.value}.${userUID.value}`);- const getStorage = () => {- return new WebStorageHelper(keyNamespace.value);- };- const keyForTab = (id: string) => {- return `tab.${id}`;- };- const loadStoredTab = (id: string) => {- const stored = getStorage().load<PersistentTab | undefined>(- keyForTab(id),- undefined- );- if (!stored) {- return undefined;- }- const tab = reactive<SQLEditorTab>({- ...defaultSQLEditorTab(),- // Ignore extended fields stored in localStorage since they are migrated- // to extendedTabStore.- ...omit(stored, EXTENDED_TAB_FIELDS),- id,- });- if (tab.mode !== DEFAULT_SQL_EDITOR_TAB_MODE) {- // Do not enter ADMIN mode initially- tab.mode = DEFAULT_SQL_EDITOR_TAB_MODE;- }-- fetchExtendedTab(tab, () => {- // When the first time of migration, the extended doc in IndexedDB is not- // found.- // Fallback to the original PersistentTab in LocalStorage if possible.- // This might happen only once to each user, since the second time when a- // tab is saved, extended fields will be migrated, and won't be saved to- // LocalStorage, so the fallback routine won't be hit.- const { statement } = stored as any;- if (statement) {- tab.statement = statement;+ const loadStoredTabs = async () => {+ const validTabList: PersistentTab[] = [];+ for (const tab of openTabList.value) {+ let fullTab: SQLEditorTab | undefined;+ if (tab.worksheet) {+ const worksheet = await worksheetStore.getOrFetchWorksheetByName(+ tab.worksheet,+ true+ );+ if (!worksheet) {+ continue;+ }+ const statement = getSheetStatement(worksheet);+ const connection = await extractWorksheetConnection(worksheet);++ fullTab = {+ ...defaultSQLEditorTab(),+ ...tab,+ connection,+ worksheet: worksheet.name,+ title: worksheet.title,+ statement,+ status: "CLEAN",+ };+ } else {+ const draft = draftTabList.value.find((item) => item.id === tab.id);+ if (!draft) {+ continue;+ }+ fullTab = draft;+ }+ if (!fullTab) {+ continue;}- });- // Don't watch the tab here - only watch the current active tab- tabsById.set(id, tab);- return tab;- };+ validTabList.push(tab);+ tabsById.set(tab.id, fullTab);+ }- const tabIdListKey = computed(() => `${keyNamespace.value}.tab-id-list`);- const tabIdListMapByProject = useDynamicLocalStorage<- Record<string, string[]>- >(tabIdListKey, {});+ openTabList.value = validTabList;+ };- const currentTabIdKey = computed(- () => `${keyNamespace.value}.current-tab-id`+ const draftTabList = useDynamicLocalStorage<SQLEditorTab[]>(+ computed(() => `${keyNamespace.value}.draft-tab-list`),+ [],+ localStorage,+ {+ listenToStorageChanges: true,+ });- const currentTabIdMapByProject = useDynamicLocalStorage<- Record<string, string | undefined>- >(currentTabIdKey, {}, localStorage, {- listenToStorageChanges: false,- });- const initializedProjects = new Set<string>();- const maybeInitProject = (project: string) => {- if (!project) {- return;- }- if (initializedProjects.has(project)) {- return;+ const openTabList = useDynamicLocalStorage<PersistentTab[]>(+ computed(() => `${keyNamespace.value}.opening-tab-list`),+ [],+ localStorage,+ {+ listenToStorageChanges: false,}+ );- const storedTabIdList = tabIdListMapByProject.value[project] ?? [];- // Load tabs- const validTabIdList: string[] = [];- storedTabIdList.forEach((id) => {- const stored = loadStoredTab(id);- if (!stored) return;- validTabIdList.push(id);- });-- tabIdListMapByProject.value[project] = validTabIdList;-- // Load currentTabId- const storedCurrentTabId = currentTabIdMapByProject.value[project];- if (!storedCurrentTabId || !validTabIdList.includes(storedCurrentTabId)) {- // storedCurrentTabId is not in tabIdList- // fallback to the first tab or nothing- currentTabIdMapByProject.value[project] = head(validTabIdList) ?? "";+ const currentTabId = useDynamicLocalStorage<string>(+ computed(() => `${keyNamespace.value}.current-tab-id`),+ "",+ localStorage,+ {+ listenToStorageChanges: false,}+ );- initializedProjects.add(project);+ const maybeInitProject = async () => {+ tabsById.clear();+ await loadStoredTabs();+ currentTabId.value = head(openTabList.value)?.id ?? "";};- // computed states- // `tabIdList` is the tabIdList in current project- // it's a combination of `project` and `tabIdListMapByProject`- const tabIdList = computed({- get() {- return tabIdListMapByProject.value[project.value] ?? [];- },- set(list) {- tabIdListMapByProject.value[project.value] = list;- },- });- // `currentTabId` is the currentTabId in current project- // it's a combination of `project` and `currentTabIdMapByProject`- const currentTabId = computed({- get() {- return currentTabIdMapByProject.value[project.value] ?? "";- },- set(id) {- currentTabIdMapByProject.value[project.value] = id;- },- });const tabById = (id: string) => {- const existed = tabsById.get(id);- if (existed) {- return existed;- }- const stored = loadStoredTab(id);- return stored;+ return tabsById.get(id);};+const tabList = computed(() => {- return tabIdList.value.map((id) => {- return tabById(id) ?? defaultSQLEditorTab();+ return openTabList.value.map((item) => {+ return tabById(item.id) ?? defaultSQLEditorTab();});});const currentTab = computed(() => {@@ -232,41 +181,75 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {...defaultSQLEditorTab(),...payload,});- const { id } = newTab;- const position = tabIdList.value.indexOf(currentTabId.value ?? "");+ const { id, worksheet } = newTab;++ const persistentTab = pick(+ newTab,+ ...PERSISTENT_TAB_FIELDS+ ) as PersistentTab;+ const position = openTabList.value.findIndex(+ (item) => item.id === currentTabId.value+ );if (beside && position >= 0) {- tabIdList.value.splice(position + 1, 0, id);+ openTabList.value.splice(position + 1, 0, persistentTab);} else {- tabIdList.value.push(id);+ openTabList.value.push(persistentTab);+ }+ if (!worksheet) {+ draftTabList.value.push(newTab);}+setCurrentTabId(id);tabsById.set(id, newTab);return newTab;};- const removeTab = (tab: SQLEditorTab) => {++ const removeDraft = (tab: SQLEditorTab) => {+ const draftIndex = draftTabList.value.findIndex(+ (item) => item.id === tab.id+ );+ if (draftIndex >= 0) {+ draftTabList.value.splice(draftIndex, 1);+ }+ };++ const closeTab = (tab: SQLEditorTab) => {const { id } = tab;- const position = tabIdList.value.indexOf(id);- if (position < 0) return;- tabIdList.value.splice(position, 1);+ const position = openTabList.value.findIndex((item) => item.id === id);+ if (position < 0) {+ return;+ }+ openTabList.value.splice(position, 1);tabsById.delete(id);- getStorage().remove(keyForTab(id));- deleteExtendedTab(tab);if (tab.mode === "ADMIN") {useWebTerminalStore().clearQueryStateByTab(id);}++ if (id === currentTabId.value) {+ const nextIndex = Math.min(position, openTabList.value.length - 1);+ const nextTab = openTabList.value[nextIndex];+ setCurrentTabId(nextTab?.id ?? "");+ }};+const updateTab = (id: string, payload: Partial<SQLEditorTab>) => {const tab = tabById(id);if (!tab) return;Object.assign(tab, payload);++ if (payload.worksheet) {+ removeDraft(tab);+ }};+const updateCurrentTab = (payload: Partial<SQLEditorTab>) => {const id = currentTabId.value;if (!id) return;updateTab(id, payload);};+const updateBatchQueryContext = (payload: Partial<BatchQueryContext>) => {const tab = currentTab.value;if (!tab) {@@ -410,18 +393,13 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {);}};- // Load tabs session from localStorage- // Reset if failed- const initAll = () => {- const projects = Object.keys(tabIdListMapByProject.value);- // initialize all stored projects- projects.forEach((project) => {- maybeInitProject(project);- });- // initialize current project if needed (when it's not stored)- maybeInitProject(project.value);- };- initAll();++ watch(+ () => project.value,+ () => {+ maybeInitProject();+ }+ );// some shortcutsconst isDisconnected = computed(() => {@@ -430,70 +408,16 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {return isDisconnectedSQLEditorTab(tab);});- const isSwitchingTab = ref(false);-- // Track the currently watched tab to clean up old watchers- let currentWatchedTabStop: (() => void) | null = null;-- watch(- currentTabId,- (tabId) => {- isSwitchingTab.value = true;- nextTick(() => {- isSwitchingTab.value = false;- });-- // Clean up the old tab watcher- if (currentWatchedTabStop) {- currentWatchedTabStop();- currentWatchedTabStop = null;- }-- // Watch only the current active tab- if (tabId) {- currentWatchedTabStop = watchThrottled(- () => {- // Get the tab from the reactive map each time- const activeTab = tabsById.get(tabId);- if (!activeTab) return null;- return {- persistent: pick(- activeTab,- ...PERSISTENT_TAB_FIELDS- ) as PersistentTab,- extended: pick(activeTab, ...EXTENDED_TAB_FIELDS) as ExtendedTab,- };- },- (value) => {- if (!value) return;- const { persistent, extended } = value;- getStorage().save<PersistentTab>(- keyForTab(persistent.id),- persistent- );- const activeTab = tabsById.get(persistent.id);- if (activeTab) {- saveExtendedTab(activeTab, extended);- }- },- { deep: true, immediate: true, throttle: 300, trailing: true }- );- }- },- {- immediate: true,- }- );-return {project,- tabIdList,tabList,+ draftList: computed(() => draftTabList.value),currentTabId,currentTab,tabById,addTab,- removeTab,+ removeDraft,+ closeTab,updateTab,updateCurrentTab,updateBatchQueryContext,@@ -505,7 +429,6 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {selectOrAddSimilarNewTab,maybeInitProject,isDisconnected,- isSwitchingTab,isInBatchMode,supportBatchMode,};diff --git a/frontend/src/utils/v1/worksheet.ts b/frontend/src/utils/v1/worksheet.tsindex 0de908a559..e2296389d5 100644--- a/frontend/src/utils/v1/worksheet.ts+++ b/frontend/src/utils/v1/worksheet.ts@@ -1,9 +1,24 @@-import { useCurrentUserV1, useProjectV1Store } from "@/store";+import { head } from "lodash-es";+import {+ useCurrentUserV1,+ useDatabaseV1Store,+ useProjectV1Store,+} from "@/store";import { extractUserId } from "@/store/modules/v1/common";-import { UNKNOWN_PROJECT_NAME } from "@/types";+import {+ type ComposedDatabase,+ type SQLEditorConnection,+ UNKNOWN_PROJECT_NAME,+} from "@/types";+import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";import type { Worksheet } from "@/types/proto-es/v1/worksheet_service_pb";import { Worksheet_Visibility } from "@/types/proto-es/v1/worksheet_service_pb";-import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";+import {+ emptySQLEditorConnection,+ hasProjectPermissionV2,+ hasWorkspacePermissionV2,+ isDatabaseV1Queryable,+} from "@/utils";export const extractWorksheetUID = (name: string) => {const pattern = /(?:^|\/)worksheets\/([^/]+)(?:$|\/)/;@@ -73,3 +88,44 @@ export const isWorksheetWritableV1 = (sheet: Worksheet) => {return false;};++export const setDefaultDataSourceForConn = (+ conn: SQLEditorConnection,+ database: ComposedDatabase+) => {+ if (conn.dataSourceId) {+ return;+ }++ // Default connect to the first read-only data source if available.+ // Skip checking env/project policy for now.+ const defaultDataSource =+ head(+ database.instanceResource.dataSources.filter(+ (d) => d.type === DataSourceType.READ_ONLY+ )+ ) || head(database.instanceResource.dataSources);+ if (defaultDataSource) {+ conn.dataSourceId = defaultDataSource.id;+ }+};++export const extractWorksheetConnection = async (worksheet: Worksheet) => {+ const connection = emptySQLEditorConnection();+ if (worksheet.database) {+ try {+ const database = await useDatabaseV1Store().getOrFetchDatabaseByName(+ worksheet.database+ );+ if (!isDatabaseV1Queryable(database)) {+ return connection;+ }+ connection.instance = database.instance;+ connection.database = database.name;+ setDefaultDataSourceForConn(connection, database);+ } catch {+ // Skip.+ }+ }+ return connection;+};diff --git a/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vueindex e4ac456d0a..eb9c81dd63 100644--- a/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue+++ b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue@@ -462,7 +462,7 @@ const deleteWorksheets = async (worksheets: string[]) => {for (const worksheet of worksheets) {const tab = tabStore.tabList.find((tab) => tab.worksheet === worksheet);if (tab) {- tabStore.removeTab(tab);+ tabStore.closeTab(tab);removeViewState(tab.id);}}diff --git a/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/TreeNodeSuffix.vue b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/TreeNodeSuffix.vueindex 444868089a..ffd36ecb46 100644--- a/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/TreeNodeSuffix.vue+++ b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/TreeNodeSuffix.vue@@ -125,11 +125,12 @@ const creatorForSheet = (creator: string) => {const handleDeleteDraft = () => {if (props.node.worksheet && props.node.worksheet.name) {- const draft = tabStore.tabList.find(+ const draft = tabStore.draftList.find((t) => t.id === props.node.worksheet!.name);if (draft) {- tabStore.removeTab(draft);+ tabStore.closeTab(draft);+ tabStore.removeDraft(draft);}removeViewState(props.node.worksheet.name);}diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsxindex 5e5cf62a9f..cbc360c841 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx@@ -26,10 +26,10 @@ import {hasWorkspacePermissionV2,instanceV1HasAlterSchema,instanceV1HasReadonlyMode,+ setDefaultDataSourceForConn,tryConnectToCoreSQLEditorTab,} from "@/utils";import { type SQLEditorContext, useSQLEditorContext } from "../../context";-import { setDefaultDataSourceForConn } from "../../EditorCommon";type DropdownOptionWithTreeNode = DropdownOption & {onSelect: () => void;diff --git a/frontend/src/views/sql-editor/EditorCommon/utils.ts b/frontend/src/views/sql-editor/EditorCommon/utils.tsindex d922beb765..d57da47842 100644--- a/frontend/src/views/sql-editor/EditorCommon/utils.ts+++ b/frontend/src/views/sql-editor/EditorCommon/utils.ts@@ -1,7 +1,3 @@-import { head } from "lodash-es";-import type { ComposedDatabase, SQLEditorConnection } from "@/types";-import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";-const KEY_WITH_POSITION_DELIMITER = "###";export const keyWithPosition = (key: string, position: number) => {@@ -13,24 +9,3 @@ export const extractKeyWithPosition = (key: string) => {const position = parseInt(maybePosition, 10);return [maybeKey, Number.isNaN(position) ? -1 : position];};--export const setDefaultDataSourceForConn = (- conn: SQLEditorConnection,- database: ComposedDatabase-) => {- if (conn.dataSourceId) {- return;- }-- // Default connect to the first read-only data source if available.- // Skip checking env/project policy for now.- const defaultDataSource =- head(- database.instanceResource.dataSources.filter(- (d) => d.type === DataSourceType.READ_ONLY- )- ) || head(database.instanceResource.dataSources);- if (defaultDataSource) {- conn.dataSourceId = defaultDataSource.id;- }-};diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vueindex 573beeedfd..58d587ae9f 100644--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue@@ -84,7 +84,7 @@ const {pendingInsertAtCaret,events: editorEvents,} = useSQLEditorContext();-const { currentTab, isSwitchingTab } = storeToRefs(tabStore);+const { currentTab } = storeToRefs(tabStore);const AIContext = useAIContext();const monacoEditorRef = ref<InstanceType<typeof MonacoEditor>>();@@ -112,11 +112,6 @@ const filename = computed(() => {});const handleUpdateStatement = (value: string) => {- // When we are switching between tabs, the MonacoEditor emits a 'change'- // event, but we shouldn't update the current tab;- if (isSwitchingTab.value) {- return;- }const tab = currentTab.value;if (!tab || value === tab.statement) {return;diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vueindex 27ea72b027..41400ab840 100644--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue+++ b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue@@ -79,7 +79,7 @@ const tabStore = useSQLEditorTabStore();const { events: editorEvents } = useSQLEditorContext();const { connection, instance, database } = useConnectionOfCurrentSQLEditorTab();const language = useInstanceV1EditorLanguage(instance);-const { currentTab, isSwitchingTab } = storeToRefs(tabStore);+const { currentTab } = storeToRefs(tabStore);const pendingFormatContentCommand = ref(false);const dialect = computed((): SQLDialect => {const engine = instance.value.engine;@@ -112,12 +112,6 @@ const debouncedEmitUpdate = debounce((value: string) => {}, 100);const handleChange = (value: string) => {- // When we are switching between tabs, the MonacoEditor emits a 'change'- // event, but we shouldn't update the current tab;- if (isSwitchingTab.value) {- return;- }-// Use debounced emit to reduce excessive updatesdebouncedEmitUpdate(value);};diff --git a/frontend/src/views/sql-editor/Sheet/context.ts b/frontend/src/views/sql-editor/Sheet/context.tsindex 97c5195a94..b1a7f39137 100644--- a/frontend/src/views/sql-editor/Sheet/context.ts+++ b/frontend/src/views/sql-editor/Sheet/context.ts@@ -10,7 +10,6 @@ import { t } from "@/plugins/i18n";import {pushNotification,useCurrentUserV1,- useDatabaseV1Store,useSQLEditorStore,useSQLEditorTabStore,useWorkSheetStore,@@ -23,14 +22,13 @@ import {} from "@/types/proto-es/v1/worksheet_service_pb";import {emptySQLEditorConnection,+ extractWorksheetConnection,getSheetStatement,- isDatabaseV1Queryable,isWorksheetReadableV1,suggestedTabTitleForSQLEditorConnection,useDynamicLocalStorage,} from "@/utils";import type { SQLEditorContext } from "../context";-import { setDefaultDataSourceForConn } from "../EditorCommon";import { useFolderByView } from "./folder";import type { SheetViewMode } from "./types";@@ -135,14 +133,12 @@ const useSheetTreeByView = (case "shared":return worksheetList.value.map(convertToWorksheetLikeItem);case "draft":- return tabStore.tabList- .filter((tab) => !tab.worksheet)- .map((tab) => ({- name: tab.id,- title: tab.title,- folders: [],- type: "draft",- }));+ return tabStore.draftList.map((tab) => ({+ name: tab.id,+ title: tab.title,+ folders: [],+ type: "draft",+ }));default:return [];}@@ -313,7 +309,7 @@ const useSheetTreeByView = ();break;default:- return;+ break;}rebuildTree();@@ -544,26 +540,6 @@ export const provideSheetContext = () => {return context;};-export const extractWorksheetConnection = async (worksheet: Worksheet) => {- const connection = emptySQLEditorConnection();- if (worksheet.database) {- try {- const database = await useDatabaseV1Store().getOrFetchDatabaseByName(- worksheet.database- );- if (!isDatabaseV1Queryable(database)) {- return connection;- }- connection.instance = database.instance;- connection.database = database.name;- setDefaultDataSourceForConn(connection, database);- } catch {- // Skip.- }- }- return connection;-};-export const openWorksheetByName = async (name: string,editorContext: SQLEditorContext,diff --git a/frontend/src/views/sql-editor/TabList/TabList.vue b/frontend/src/views/sql-editor/TabList/TabList.vueindex fa565c878a..b8e328d923 100644--- a/frontend/src/views/sql-editor/TabList/TabList.vue+++ b/frontend/src/views/sql-editor/TabList/TabList.vue@@ -13,7 +13,7 @@<Draggableid="tab-list"ref="tabListRef"- v-model="tabStore.tabIdList"+ v-model="tabStore.tabList"item-key="id"animation="300"class="relative flex flex-nowrap overflow-hidden h-9 pt-0.5 hide-scrollbar"@@ -26,16 +26,16 @@@end="state.dragging = false"><template- #item="{ element: id, index }: { element: string; index: number }"+ #item="{ element: tab, index }: { element: SQLEditorTab; index: number }"><TabItem- :tab="tabStore.tabById(id)!"+ :tab="tab":index="index"- :data-tab-id="id"- @select="(tab) => handleSelectTab(tab)"- @close="(tab, index) => handleRemoveTab(tab, index)"+ :data-tab-id="tab.id"+ @select="(tab) => tabStore.setCurrentTabId(tab.id)"+ @close="(tab) => handleRemoveTab(tab)"@contextmenu.stop.prevent="- contextMenuRef?.show(tabStore.tabById(id)!, index, $event)+ contextMenuRef?.show(tab, index, $event)"/></template>@@ -112,10 +112,6 @@ const scrollElement = computed((): HTMLElement | null | undefined => {return scrollbarRef.value?.scrollbarInstRef?.containerRef;});-const handleSelectTab = async (tab: SQLEditorTab | undefined) => {- tabStore.setCurrentTabId(tab?.id ?? "");-};-const handleAddTab = () => {tabStore.addTab();@@ -133,11 +129,7 @@ const handleAddTab = () => {});};-const handleRemoveTab = async (- tab: SQLEditorTab,- index: number,- focusWhenConfirm = false-) => {+const handleRemoveTab = async (tab: SQLEditorTab, focusWhenConfirm = false) => {const _defer = defer<boolean>();if (tab.mode === "WORKSHEET" && tab.status === "DIRTY") {if (focusWhenConfirm) {@@ -152,7 +144,7 @@ const handleRemoveTab = async (maskClosable: false,closeOnEsc: false,onPositiveClick() {- remove(index);+ remove();$dialog.destroy();_defer.resolve(true);},@@ -165,19 +157,14 @@ const handleRemoveTab = async (showIcon: false,});} else {- remove(index);+ remove();_defer.resolve(true);}- function remove(index: number) {- tabStore.removeTab(tab);+ function remove() {+ tabStore.closeTab(tab);removeViewState(tab.id);- // select a tab near the removed tab.- const nextIndex = Math.min(index, tabStore.tabList.length - 1);- const nextTab = tabStore.tabList[nextIndex];- handleSelectTab(nextTab);-nextTick(recalculateScrollState);}@@ -245,28 +232,28 @@ useEmitteryEventListener(async ({ tab, index, action }) => {const { tabList } = tabStore;- const remove = async (tab: SQLEditorTab, index: number) => {- await handleRemoveTab(tab, index, true);+ const remove = async (tab: SQLEditorTab) => {+ await handleRemoveTab(tab, true);await new Promise((r) => requestAnimationFrame(r));};if (action === "CLOSE") {- await remove(tab, index);+ await remove(tab);return;}const max = tabList.length - 1;if (action === "CLOSE_OTHERS") {for (let i = max; i > index; i--) {- await remove(tabList[i], i);+ await remove(tabList[i]);}for (let i = index - 1; i >= 0; i--) {- await remove(tabList[i], i);+ await remove(tabList[i]);}return;}if (action === "CLOSE_TO_THE_RIGHT") {for (let i = max; i > index; i--) {- await remove(tabList[i], i);+ await remove(tabList[i]);}return;}@@ -274,14 +261,14 @@ useEmitteryEventListener(for (let i = max; i >= 0; i--) {const tab = tabList[i];if (tab.status === "CLEAN") {- await remove(tab, i);+ await remove(tab);}}return;}if (action === "CLOSE_ALL") {for (let i = max; i >= 0; i--) {- await remove(tabList[i], i);+ await remove(tabList[i]);}}}