Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(grid): reconcile localStorage index and clean up orphan column width entries (#12914)

lxk9551fef24357ddb
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridColumnWidthState.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridColumnWidthState.spec.ts
index 31d16c6f22..7cd6fa906c 100644
--- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridColumnWidthState.spec.ts
+++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridColumnWidthState.spec.ts
@@ -1,7 +1,16 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { clearDataGridColumnWidthStates, createDataGridColumnMeasurementSignature, createDataGridColumnStructureSignature, DATA_GRID_COLUMN_WIDTH_STATE_LIMIT, loadDataGridColumnWidthState, removeDataGridColumnWidthState, saveDataGridColumnWidthState } from "@/lib/dataGrid/dataGridColumnWidthState";
+import {
+ clearDataGridColumnWidthStates,
+ createDataGridColumnMeasurementSignature,
+ createDataGridColumnStructureSignature,
+ DATA_GRID_COLUMN_WIDTH_STATE_LIMIT,
+ loadDataGridColumnWidthState,
+ reconcileDataGridColumnWidthStorageIndex,
+ removeDataGridColumnWidthState,
+ saveDataGridColumnWidthState,
+} from "@/lib/dataGrid/dataGridColumnWidthState";
describe("dataGridColumnWidthState", () => {
const structureSignature = createDataGridColumnStructureSignature(["id", "name"], ["INT", "VARCHAR"]);
@@ -98,4 +107,114 @@ describe("dataGridColumnWidthState", () => {
// Latest should exist
expect(localStorage.getItem(`dbx-data-grid-column-widths:item-${DATA_GRID_COLUMN_WIDTH_STATE_LIMIT + 4}`)).toBeTruthy();
});
+
+ it("prunes orphan index entries on read when data is missing from localStorage", () => {
+ const validIdentity = { cacheKey: "valid-key", structureSignature, measurementSignature };
+ saveDataGridColumnWidthState(validIdentity, [0], [150], new Set([0]));
+
+ // Manually inject an orphan key into the index (simulating a stale entry from a closed/evicted window)
+ const index = JSON.parse(localStorage.getItem("dbx-data-grid-column-widths-index") || "[]") as string[];
+ index.unshift("orphan-key");
+ localStorage.setItem("dbx-data-grid-column-widths-index", JSON.stringify(index));
+
+ // Trying to load the orphan key should return undefined and prune it from the index
+ const loaded = loadDataGridColumnWidthState({ cacheKey: "orphan-key", structureSignature, measurementSignature }, [0]);
+ expect(loaded).toBeUndefined();
+
+ const updatedIndex = JSON.parse(localStorage.getItem("dbx-data-grid-column-widths-index") || "[]") as string[];
+ expect(updatedIndex).not.toContain("orphan-key");
+ expect(updatedIndex).toContain("valid-key");
+ });
+
+ it("prunes orphan index entries pointing to missing data during write reconciliation", () => {
+ const validIdentity = { cacheKey: "valid-key", structureSignature, measurementSignature };
+ saveDataGridColumnWidthState(validIdentity, [0], [150], new Set([0]));
+
+ // Manually inject an orphan key into the index
+ const index = JSON.parse(localStorage.getItem("dbx-data-grid-column-widths-index") || "[]") as string[];
+ index.push("stale-ghost-key");
+ localStorage.setItem("dbx-data-grid-column-widths-index", JSON.stringify(index));
+
+ // Writing a new state triggers reconciliation
+ const nextIdentity = { cacheKey: "new-key", structureSignature, measurementSignature };
+ saveDataGridColumnWidthState(nextIdentity, [0], [200], new Set([0]));
+
+ const updatedIndex = JSON.parse(localStorage.getItem("dbx-data-grid-column-widths-index") || "[]") as string[];
+ expect(updatedIndex).not.toContain("stale-ghost-key");
+ expect(updatedIndex).toEqual(["valid-key", "new-key"]);
+ });
+
+ it("adopts orphan data entries from concurrent multi-window writes and includes them in LRU eviction", () => {
+ // Simulate another window writing a data item directly without updating the index (or index write lost to race)
+ const orphanDataPayload = JSON.stringify({
+ version: 1,
+ structureSignature,
+ measurementSignature,
+ widths: [[0, 180]],
+ userSizedColumnIndexes: [0],
+ });
+ localStorage.setItem("dbx-data-grid-column-widths:concurrent-orphan", orphanDataPayload);
+ // Index currently does NOT contain "concurrent-orphan"
+ expect(JSON.parse(localStorage.getItem("dbx-data-grid-column-widths-index") || "[]")).not.toContain("concurrent-orphan");
+
+ // Reconcile or trigger save from current window
+ const reconciled = reconcileDataGridColumnWidthStorageIndex();
+ expect(reconciled).toContain("concurrent-orphan");
+
+ // Write enough items to exceed the limit
+ for (let i = 0; i < DATA_GRID_COLUMN_WIDTH_STATE_LIMIT; i++) {
+ saveDataGridColumnWidthState({ cacheKey: `fill-${i}`, structureSignature, measurementSignature }, [0], [100 + i], new Set([0]));
+ }
+
+ // Since concurrent-orphan was adopted at the oldest end, it should be evicted when capacity is reached
+ expect(localStorage.getItem("dbx-data-grid-column-widths:concurrent-orphan")).toBeNull();
+ });
+
+ it("cleans up all orphan data entries on clearDataGridColumnWidthStates even if omitted from index", () => {
+ // Store valid item
+ saveDataGridColumnWidthState({ cacheKey: "indexed-item", structureSignature, measurementSignature }, [0], [120], new Set([0]));
+
+ // Directly insert an unindexed orphan item
+ localStorage.setItem("dbx-data-grid-column-widths:unindexed-orphan", JSON.stringify({ version: 1, structureSignature, measurementSignature, widths: [[0, 100]], userSizedColumnIndexes: [0] }));
+
+ clearDataGridColumnWidthStates();
+
+ // Both indexed item and orphan data item must be cleared
+ expect(localStorage.getItem("dbx-data-grid-column-widths:indexed-item")).toBeNull();
+ expect(localStorage.getItem("dbx-data-grid-column-widths:unindexed-orphan")).toBeNull();
+ expect(localStorage.getItem("dbx-data-grid-column-widths-index")).toBeNull();
+ });
+
+ it("deduplicates corrupted or raced index entries", () => {
+ saveDataGridColumnWidthState({ cacheKey: "dup-1", structureSignature, measurementSignature }, [0], [100], new Set([0]));
+ saveDataGridColumnWidthState({ cacheKey: "dup-2", structureSignature, measurementSignature }, [0], [200], new Set([0]));
+
+ // Artificially inject duplicate keys into index
+ localStorage.setItem("dbx-data-grid-column-widths-index", JSON.stringify(["dup-1", "dup-1", "dup-2", "dup-2"]));
+
+ const reconciled = reconcileDataGridColumnWidthStorageIndex();
+ expect(reconciled).toEqual(["dup-1", "dup-2"]);
+ });
+
+ it("preserves keys across simulated concurrent writes from multiple windows", () => {
+ // Window A writes item A
+ saveDataGridColumnWidthState({ cacheKey: "winA-1", structureSignature, measurementSignature }, [0], [100], new Set([0]));
+
+ // Window B concurrently writes item B directly into localStorage, with an index that didn't know about winA-1
+ localStorage.setItem("dbx-data-grid-column-widths:winB-1", JSON.stringify({ version: 1, structureSignature, measurementSignature, widths: [[0, 150]], userSizedColumnIndexes: [0] }));
+ // Window B overwrites index to only contain winB-1
+ localStorage.setItem("dbx-data-grid-column-widths-index", JSON.stringify(["winB-1"]));
+
+ // Window A now writes item A2
+ saveDataGridColumnWidthState({ cacheKey: "winA-2", structureSignature, measurementSignature }, [0], [200], new Set([0]));
+
+ // All three items must be in the index: winA-1 (adopted), winB-1, winA-2
+ const finalIndex = JSON.parse(localStorage.getItem("dbx-data-grid-column-widths-index") || "[]") as string[];
+ expect(finalIndex).toContain("winA-1");
+ expect(finalIndex).toContain("winB-1");
+ expect(finalIndex).toContain("winA-2");
+ expect(localStorage.getItem("dbx-data-grid-column-widths:winA-1")).toBeTruthy();
+ expect(localStorage.getItem("dbx-data-grid-column-widths:winB-1")).toBeTruthy();
+ expect(localStorage.getItem("dbx-data-grid-column-widths:winA-2")).toBeTruthy();
+ });
});
diff --git a/apps/desktop/src/lib/backend/__tests__/safeStorage.spec.ts b/apps/desktop/src/lib/backend/__tests__/safeStorage.spec.ts
new file mode 100644
index 0000000000..a403360389
--- /dev/null
+++ b/apps/desktop/src/lib/backend/__tests__/safeStorage.spec.ts
@@ -0,0 +1,33 @@
+// @vitest-environment happy-dom
+
+import { beforeEach, describe, expect, it } from "vitest";
+import { safeLocalStorageGet, safeLocalStorageKeys, safeLocalStorageRemove, safeLocalStorageSet } from "@/lib/backend/safeStorage";
+
+describe("safeStorage", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ it("gets, sets, and removes values safely", () => {
+ expect(safeLocalStorageGet("test-key")).toBeNull();
+ expect(safeLocalStorageSet("test-key", "hello")).toBe(true);
+ expect(safeLocalStorageGet("test-key")).toBe("hello");
+
+ safeLocalStorageRemove("test-key");
+ expect(safeLocalStorageGet("test-key")).toBeNull();
+ });
+
+ it("lists all keys via safeLocalStorageKeys", () => {
+ expect(safeLocalStorageKeys()).toEqual([]);
+
+ safeLocalStorageSet("k1", "v1");
+ safeLocalStorageSet("k2", "v2");
+ safeLocalStorageSet("k3", "v3");
+
+ const keys = safeLocalStorageKeys();
+ expect(keys).toHaveLength(3);
+ expect(keys).toContain("k1");
+ expect(keys).toContain("k2");
+ expect(keys).toContain("k3");
+ });
+});
diff --git a/apps/desktop/src/lib/backend/safeStorage.ts b/apps/desktop/src/lib/backend/safeStorage.ts
index d91eb83731..99eb5a48e6 100644
--- a/apps/desktop/src/lib/backend/safeStorage.ts
+++ b/apps/desktop/src/lib/backend/safeStorage.ts
@@ -30,3 +30,20 @@ export function safeLocalStorageRemove(key: string) {
storageWarn("remove", key, error);
}
}
+
+export function safeLocalStorageKeys(): string[] {
+ try {
+ const storage = globalThis.localStorage;
+ if (!storage) return [];
+ const keys: string[] = [];
+ const len = storage.length;
+ for (let i = 0; i < len; i++) {
+ const key = storage.key(i);
+ if (key !== null) keys.push(key);
+ }
+ return keys;
+ } catch (error) {
+ storageWarn("keys", "", error);
+ return [];
+ }
+}
diff --git a/apps/desktop/src/lib/dataGrid/dataGridColumnWidthState.ts b/apps/desktop/src/lib/dataGrid/dataGridColumnWidthState.ts
index 414a9dc561..be27fcd3bc 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridColumnWidthState.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridColumnWidthState.ts
@@ -1,4 +1,4 @@
-import { safeLocalStorageGet, safeLocalStorageRemove, safeLocalStorageSet } from "@/lib/backend/safeStorage";
+import { safeLocalStorageGet, safeLocalStorageKeys, safeLocalStorageRemove, safeLocalStorageSet } from "@/lib/backend/safeStorage";
import type { ColumnWidthDensity } from "@/stores/settingsStore";
export const DATA_GRID_COLUMN_WIDTH_STATE_LIMIT = 128;
@@ -46,7 +46,7 @@ function loadStorageIndex(): string[] {
if (!raw) return [];
try {
const parsed = JSON.parse(raw);
- return Array.isArray(parsed) ? parsed.filter((key): key is string => typeof key === "string") : [];
+ return Array.isArray(parsed) ? parsed.filter((key): key is string => typeof key === "string" && key.length > 0) : [];
} catch {
return [];
}
@@ -56,9 +56,54 @@ function saveStorageIndex(index: string[]) {
safeLocalStorageSet(STORAGE_INDEX_KEY, JSON.stringify(index));
}
+function getActualStorageKeys(): Set<string> {
+ const keys = safeLocalStorageKeys();
+ const actualKeys = new Set<string>();
+ for (const key of keys) {
+ if (key.startsWith(STORAGE_PREFIX)) {
+ actualKeys.add(key.slice(STORAGE_PREFIX.length));
+ }
+ }
+ return actualKeys;
+}
+
+function reconcileStorageIndex(activeKey?: string): string[] {
+ const currentIndex = loadStorageIndex();
+ const actualDataKeys = getActualStorageKeys();
+
+ if (currentIndex.length === 0 && actualDataKeys.size === 0) {
+ return activeKey ? [activeKey] : [];
+ }
+
+ const seen = new Set<string>();
+ const validIndex: string[] = [];
+
+ // 1. Keep indexed keys that actually have data in storage, preserving order (prunes orphan index entries)
+ for (const key of currentIndex) {
+ if (actualDataKeys.has(key) && !seen.has(key) && key !== activeKey) {
+ seen.add(key);
+ validIndex.push(key);
+ }
+ }
+
+ // 2. Adopt unindexed stored keys (recovers orphan data entries from concurrent multi-window writes)
+ for (const dataKey of actualDataKeys) {
+ if (!seen.has(dataKey) && dataKey !== activeKey) {
+ seen.add(dataKey);
+ validIndex.unshift(dataKey);
+ }
+ }
+
+ // 3. Place activeKey at the most-recent end
+ if (activeKey) {
+ validIndex.push(activeKey);
+ }
+
+ return validIndex;
+}
+
function touchStorageKey(cacheKey: string) {
- const index = loadStorageIndex().filter((key) => key !== cacheKey);
- index.push(cacheKey);
+ const index = reconcileStorageIndex(cacheKey);
while (index.length > DATA_GRID_COLUMN_WIDTH_STATE_LIMIT) {
const oldest = index.shift();
if (oldest) safeLocalStorageRemove(`${STORAGE_PREFIX}${oldest}`);
@@ -67,14 +112,20 @@ function touchStorageKey(cacheKey: string) {
}
function removeStorageKey(cacheKey: string) {
+ safeLocalStorageRemove(`${STORAGE_PREFIX}${cacheKey}`);
const index = loadStorageIndex().filter((key) => key !== cacheKey);
saveStorageIndex(index);
- safeLocalStorageRemove(`${STORAGE_PREFIX}${cacheKey}`);
}
function loadPersistentDataGridColumnWidthState(cacheKey: string): DataGridColumnWidthState | undefined {
const raw = safeLocalStorageGet(`${STORAGE_PREFIX}${cacheKey}`);
- if (!raw) return undefined;
+ if (!raw) {
+ const index = loadStorageIndex();
+ if (index.includes(cacheKey)) {
+ saveStorageIndex(index.filter((key) => key !== cacheKey));
+ }
+ return undefined;
+ }
try {
const parsed = JSON.parse(raw) as Partial<StoredDataGridColumnWidthState>;
if (parsed.version !== 1 || typeof parsed.structureSignature !== "string" || typeof parsed.measurementSignature !== "string" || !Array.isArray(parsed.widths) || !Array.isArray(parsed.userSizedColumnIndexes)) {
@@ -129,6 +180,12 @@ function removePersistentDataGridColumnWidthState(cacheKey: string) {
}
function clearPersistentDataGridColumnWidthStates() {
+ const allKeys = safeLocalStorageKeys();
+ for (const key of allKeys) {
+ if (key.startsWith(STORAGE_PREFIX)) {
+ safeLocalStorageRemove(key);
+ }
+ }
const index = loadStorageIndex();
for (const key of index) {
safeLocalStorageRemove(`${STORAGE_PREFIX}${key}`);
@@ -274,3 +331,13 @@ export function clearDataGridColumnWidthStates() {
export function dataGridColumnWidthStateCount(): number {
return columnWidthStates.size;
}
+
+export function reconcileDataGridColumnWidthStorageIndex(): string[] {
+ const index = reconcileStorageIndex();
+ while (index.length > DATA_GRID_COLUMN_WIDTH_STATE_LIMIT) {
+ const oldest = index.shift();
+ if (oldest) safeLocalStorageRemove(`${STORAGE_PREFIX}${oldest}`);
+ }
+ saveStorageIndex(index);
+ return index;
+}