Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor(sql-editor): split tab large fields to IndexedDB (#14639)

Liu Ji5e3edacab6d9
diff --git a/frontend/src/store/modules/sqlEditor/extendedTab.ts b/frontend/src/store/modules/sqlEditor/extendedTab.ts
new file mode 100644
index 0000000000..020a769b8e
--- /dev/null
+++ b/frontend/src/store/modules/sqlEditor/extendedTab.ts
@@ -0,0 +1,140 @@
+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 { extractUserUID } from "@/utils";
+import { useCurrentUserV1 } from "../auth";
+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(() => extractUserUID(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.ts
index 62faa8ec0d..f24cd00927 100644
--- a/frontend/src/store/modules/sqlEditor/tab.ts
+++ b/frontend/src/store/modules/sqlEditor/tab.ts
@@ -1,6 +1,6 @@
import type { MaybeRef } from "@vueuse/core";
import { watchThrottled } from "@vueuse/core";
-import { head, pick, uniqBy } from "lodash-es";
+import { head, omit, pick, uniqBy } from "lodash-es";
import { defineStore, storeToRefs } from "pinia";
import { computed, nextTick, reactive, ref, unref, watch } from "vue";
import type {
@@ -26,6 +26,11 @@ import {
useInstanceResourceByName,
} from "../v1";
import { useSQLEditorStore } from "./editor";
+import {
+ EXTENDED_TAB_FIELDS,
+ useExtendedTabStore,
+ type ExtendedTab,
+} from "./extendedTab";
import { useWebTerminalStore } from "./webTerminal";
const LOCAL_STORAGE_KEY_PREFIX = "bb.sql-editor-tab";
@@ -36,12 +41,9 @@ const PERSISTENT_TAB_FIELDS = [
"id",
"title",
"connection",
- "statement",
"mode",
"worksheet",
"status",
- "batchQueryContext",
- "treeState",
] as const;
type PersistentTab = Pick<SQLEditorTab, (typeof PERSISTENT_TAB_FIELDS)[number]>;
@@ -53,6 +55,12 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
const { project } = storeToRefs(useSQLEditorStore());
// states
+ const {
+ fetchExtendedTab,
+ saveExtendedTab,
+ deleteExtendedTab,
+ cleanupExtendedTabs,
+ } = useExtendedTabStore();
const me = useCurrentUserV1();
const userUID = computed(() => extractUserUID(me.value.name));
const keyNamespace = computed(
@@ -75,13 +83,29 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
}
const tab = reactive<SQLEditorTab>({
...defaultSQLEditorTab(),
- ...stored,
+ // 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;
+ }
+ });
+
watchTab(tab, false /* !immediate */);
tabsById.set(id, tab);
return tab;
@@ -166,7 +190,6 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
});
});
const currentTab = computed(() => {
- // _maybeInitProject(project.value);
const currId = currentTabId.value;
if (!currId) return undefined;
return tabById(currId);
@@ -205,6 +228,7 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
tabIdList.value.splice(position, 1);
tabsById.delete(id);
getStorage().remove(keyForTab(id));
+ deleteExtendedTab(tab);
if (tab.mode === "ADMIN") {
useWebTerminalStore().clearQueryStateByTab(id);
@@ -261,7 +285,7 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
};
// clean persistent tabs that are not in the `tabIdList` anymore
const _cleanup = () => {
- const prefix = `${LOCAL_STORAGE_KEY_PREFIX}.tab.`;
+ const prefix = `${keyNamespace.value}.tab.`;
const keys = getStorage()
.keys()
.filter((key) => key.startsWith(prefix));
@@ -276,6 +300,7 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
getStorage().remove(keyForTab(id));
}
});
+ cleanupExtendedTabs(userUID.value, Array.from(flattenTabIdSet));
};
// watch the field changes of a tab, store it to localStorage
// when needed, but not to frequently (for performance consideration)
@@ -291,6 +316,13 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
},
{ deep: true, immediate, throttle: 100, trailing: true }
);
+ watchThrottled(
+ () => pick(tab, EXTENDED_TAB_FIELDS) as ExtendedTab,
+ (extended) => {
+ saveExtendedTab(tab, extended);
+ },
+ { deep: true, immediate, throttle: 100, trailing: true }
+ );
};
// Load tabs session from localStorage
// Reset if failed