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(redis): preserve pinned databases across alias updates and reconnects (#12752) (#12765)

lxk955607bfd20b7eb
diff --git a/apps/desktop/src/lib/__tests__/app/pinnedItems.spec.ts b/apps/desktop/src/lib/__tests__/app/pinnedItems.spec.ts
index de48cb3316..306dac300d 100644
--- a/apps/desktop/src/lib/__tests__/app/pinnedItems.spec.ts
+++ b/apps/desktop/src/lib/__tests__/app/pinnedItems.spec.ts
@@ -2,12 +2,15 @@ import { describe, expect, it } from "vitest";
import { reactive } from "vue";
import {
inheritNaturalTreeNodeOrder,
+ isPinnedKeyPresent,
migrateLegacyPinnedTreeNodeIds,
migrateLegacyPinnedTreeNodeOrder,
+ pinnedTreeNodeIdentityMatches,
removePinnedTreeNodesFromOrder,
reorderPinnedTreeNodeOrder,
replacePinnedTreeNodeInOrder,
syncPinnedTreeNodeStateInPlace,
+ treeNodePinIdentity,
treeNodePinKey,
updatePinnedTreeNodeInPlace,
} from "@/lib/app/pinnedItems";
@@ -329,4 +332,61 @@ describe("sidebar pinned tree nodes", () => {
expect(rebuilt.map((node) => node.id)).toEqual(["group-a", "group-b"]);
});
+
+ it("produces stable pin identity for redis-db nodes across alias and count changes", () => {
+ const node1: TreeNode = {
+ id: "redis-1:db1",
+ label: "db1 (10)",
+ type: "redis-db",
+ connectionId: "redis-1",
+ database: "1",
+ };
+ const node1WithAlias: TreeNode = {
+ id: "redis-1:db1",
+ label: "db1 · orders (15)",
+ type: "redis-db",
+ connectionId: "redis-1",
+ database: "1",
+ };
+
+ expect(treeNodePinIdentity(node1).name).toBe("db1");
+ expect(treeNodePinIdentity(node1WithAlias).name).toBe("db1");
+ expect(treeNodePinKey(node1)).toBe(treeNodePinKey(node1WithAlias));
+
+ expect(pinnedTreeNodeIdentityMatches(treeNodePinIdentity(node1), treeNodePinIdentity(node1WithAlias))).toBe(true);
+ });
+
+ it("migrates legacy redis-db pin keys with previous labels in place", () => {
+ const db1: TreeNode = {
+ id: "redis-1:db1",
+ label: "db1 · orders (20)",
+ type: "redis-db",
+ connectionId: "redis-1",
+ database: "1",
+ };
+ const db2: TreeNode = {
+ id: "redis-1:db2",
+ label: "db2 · users (5)",
+ type: "redis-db",
+ connectionId: "redis-1",
+ database: "2",
+ };
+
+ // Simulate legacy pin keys containing previous labels or bare ids
+ const oldDb2Key = "redis-1:pin:v2:" + encodeURIComponent(JSON.stringify(["2", "", "", "redis-db", "db2 (3)", "", "redis-1:db2"]));
+ const oldDb1Key = "redis-1:pin:v2:" + encodeURIComponent(JSON.stringify(["1", "", "", "redis-db", "db1 (10)", "", "redis-1:db1"]));
+ const pinnedOrder = [oldDb2Key, oldDb1Key];
+
+ const result = migrateLegacyPinnedTreeNodeOrder([db1, db2], pinnedOrder);
+ expect(result.changed).toBe(true);
+ expect(result.order).toEqual([treeNodePinKey(db2), treeNodePinKey(db1)]);
+ expect(isPinnedKeyPresent(db1, result.ids)).toBe(true);
+ expect(isPinnedKeyPresent(db2, result.ids)).toBe(true);
+
+ const nodes = [db1, db2];
+ syncPinnedTreeNodeStateInPlace(nodes, result.ids, result.order);
+ expect(nodes.map((n) => n.database)).toEqual(["2", "1"]);
+ expect(nodes[0].pinned).toBe(true);
+ expect(nodes[1].pinned).toBe(true);
+ });
});
diff --git a/apps/desktop/src/lib/app/pinnedItems.ts b/apps/desktop/src/lib/app/pinnedItems.ts
index 3533068479..e12850a9dd 100644
--- a/apps/desktop/src/lib/app/pinnedItems.ts
+++ b/apps/desktop/src/lib/app/pinnedItems.ts
@@ -35,13 +35,14 @@ export function inheritNaturalTreeNodeOrder(source: TreeNode, target: TreeNode):
}
export function treeNodePinIdentity(node: TreeNode): PinnedTreeNodeIdentity {
+ const name = node.type === "redis-db" ? node.objectName || (node.database != null && node.database !== "" ? `db${node.database}` : node.label) : node.objectName || node.tableName || node.label;
return {
connectionId: node.connectionId || "",
database: node.database || "",
schema: node.schema || "",
catalog: node.catalog || "",
type: node.type,
- name: node.objectName || node.tableName || node.label,
+ name,
signature: node.signature || "",
id: node.id,
};
@@ -83,18 +84,25 @@ export function normalizePinnedTreeNodeOrder(ids: readonly string[]): string[] {
export function pinnedTreeNodeIdentityMatches(left: PinnedTreeNodeIdentity, right: PinnedTreeNodeIdentity, canonicalize: PinnedTreeNodeIdentityCanonicalizer = (identity) => identity): boolean {
const canonicalLeft = canonicalize(left);
const canonicalRight = canonicalize(right);
- return (
- canonicalLeft.connectionId === canonicalRight.connectionId &&
- canonicalLeft.database === canonicalRight.database &&
- canonicalLeft.schema === canonicalRight.schema &&
- canonicalLeft.catalog === canonicalRight.catalog &&
- canonicalLeft.type === canonicalRight.type &&
- canonicalLeft.name === canonicalRight.name &&
- canonicalLeft.signature === canonicalRight.signature
- );
+ if (
+ canonicalLeft.connectionId !== canonicalRight.connectionId ||
+ canonicalLeft.database !== canonicalRight.database ||
+ canonicalLeft.schema !== canonicalRight.schema ||
+ canonicalLeft.catalog !== canonicalRight.catalog ||
+ canonicalLeft.type !== canonicalRight.type ||
+ canonicalLeft.signature !== canonicalRight.signature
+ ) {
+ return false;
+ }
+ if (canonicalLeft.type === "redis-db") {
+ // In Redis, databases are identified by connectionId and numeric index.
+ // Display labels change when key counts or aliases update.
+ return true;
+ }
+ return canonicalLeft.name === canonicalRight.name;
}
-function pinnedTreeNodeOrderKeyMatchesNode(key: string, node: TreeNode, canonicalize: PinnedTreeNodeIdentityCanonicalizer, legacyKeys: ReadonlySet<string> = new Set()): boolean {
+export function pinnedTreeNodeOrderKeyMatchesNode(key: string, node: TreeNode, canonicalize: PinnedTreeNodeIdentityCanonicalizer = (identity) => identity, legacyKeys: ReadonlySet<string> = new Set()): boolean {
if (key === treeNodePinKey(node) || key === node.id || legacyKeys.has(key)) return true;
const identity = parseTreeNodePinKey(key);
return !!identity && pinnedTreeNodeIdentityMatches(identity, treeNodePinIdentity(node), canonicalize);
@@ -146,7 +154,7 @@ export function migrateLegacyPinnedTreeNodeOrder(nodes: readonly TreeNode[], pin
const visit = (items: readonly TreeNode[]) => {
for (const node of items) {
const pinKey = treeNodePinKey(node);
- const legacyIndex = pinKey === node.id ? -1 : next.indexOf(node.id);
+ const legacyIndex = pinKey === node.id ? -1 : next.findIndex((key) => key !== pinKey && pinnedTreeNodeOrderKeyMatchesNode(key, node, (id) => id));
if (legacyIndex >= 0) {
const scopedIndex = next.indexOf(pinKey);
if (scopedIndex < 0) {
@@ -274,8 +282,8 @@ export function orderPinnedTreeNodes(nodes: TreeNode[], pinnedOrder: readonly st
const naturalOrder = (left: TreeNode, right: TreeNode) => naturalTreeNodeOrder(left)! - naturalTreeNodeOrder(right)!;
fixed.sort(naturalOrder);
pinned.sort((left, right) => {
- const leftRank = orderByKey.get(treeNodePinKey(left));
- const rightRank = orderByKey.get(treeNodePinKey(right));
+ const leftRank = pinnedRankForNode(left, orderByKey);
+ const rightRank = pinnedRankForNode(right, orderByKey);
if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank;
if (leftRank !== undefined) return -1;
if (rightRank !== undefined) return 1;
@@ -285,6 +293,26 @@ export function orderPinnedTreeNodes(nodes: TreeNode[], pinnedOrder: readonly st
return [...virtualGroups, ...fixed, ...pinned, ...unpinned];
}
+function pinnedRankForNode(node: TreeNode, orderByKey: Map<string, number>): number | undefined {
+ const directKey = treeNodePinKey(node);
+ const directRank = orderByKey.get(directKey);
+ if (directRank !== undefined) return directRank;
+ const legacyRank = orderByKey.get(node.id);
+ if (legacyRank !== undefined) return legacyRank;
+ for (const [key, rank] of orderByKey) {
+ if (pinnedTreeNodeOrderKeyMatchesNode(key, node, (id) => id)) return rank;
+ }
+ return undefined;
+}
+
+export function isPinnedKeyPresent(node: TreeNode, pinnedIds: Set<string>): boolean {
+ if (pinnedIds.has(treeNodePinKey(node)) || pinnedIds.has(node.id)) return true;
+ for (const key of pinnedIds) {
+ if (pinnedTreeNodeOrderKeyMatchesNode(key, node, (id) => id)) return true;
+ }
+ return false;
+}
+
function findTreeNodeLocation(nodes: TreeNode[], target: TreeNode, parent: TreeNode | null = null): { node: TreeNode; parent: TreeNode | null } | null {
const targetKey = treeNodePinKey(target);
for (const node of nodes) {
@@ -320,7 +348,7 @@ function clonePinnedTreeNode(node: TreeNode, pinnedIds: Set<string>, pinnedOrder
if (existing) return existing;
const clone: TreeNode = {
...node,
- pinned: pinnedIds.has(treeNodePinKey(node)) || pinnedIds.has(node.id),
+ pinned: isPinnedKeyPresent(node, pinnedIds),
};
clones.set(node, clone);
inheritNaturalTreeNodeOrder(node, clone);
@@ -343,7 +371,7 @@ function syncPinnedTreeNodeStateInPlaceInternal(nodes: TreeNode[], pinnedIds: Se
for (const node of nodes) {
if (visited.has(node)) continue;
visited.add(node);
- node.pinned = pinnedIds.has(treeNodePinKey(node)) || pinnedIds.has(node.id);
+ node.pinned = isPinnedKeyPresent(node, pinnedIds);
if (node.children) {
syncPinnedTreeNodeStateInPlaceInternal(node.children, pinnedIds, pinnedOrder, isFixedPriority, visited, node.type === "table-vgroup");
}
diff --git a/apps/desktop/src/stores/__tests__/connectionStore.redisAlias.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.redisAlias.spec.ts
index d79c74a083..26de50ad29 100644
--- a/apps/desktop/src/stores/__tests__/connectionStore.redisAlias.spec.ts
+++ b/apps/desktop/src/stores/__tests__/connectionStore.redisAlias.spec.ts
@@ -142,4 +142,124 @@ describe("connectionStore Redis database aliases", () => {
expect(store.connections[0]).toEqual(expect.objectContaining({ password: "one-time-secret", redis_database_aliases: { "3": "orders" } }));
expect(saveConnections).toHaveBeenLastCalledWith([]);
});
+
+ it("preserves pinned state and order for redis databases with aliases after reconnecting", async () => {
+ const saveConnections = vi.fn().mockResolvedValue(undefined);
+ const savePinnedTreeNodeIds = vi.fn().mockResolvedValue(undefined);
+ const redisListDatabases = vi.fn().mockResolvedValue([
+ { db: 0, keys: 5 },
+ { db: 1, keys: 10 },
+ { db: 2, keys: 20 },
+ ]);
+ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
+ vi.doMock("@/lib/backend/api", () => ({
+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
+ saveConnections,
+ savePinnedTreeNodeIds,
+ redisListDatabases,
+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
+ loadSchemaCache: vi.fn().mockResolvedValue(null),
+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),
+ }));
+
+ const { useConnectionStore } = await import("@/stores/connectionStore");
+ const { useSettingsStore } = await import("@/stores/settingsStore");
+ useSettingsStore().updateEditorSettings({ sidebarPinDefaultDatabase: false });
+ const store = useConnectionStore();
+ const conn = redisConnection();
+ store.connections = [conn];
+ store.connectedIds.add(conn.id);
+ store.treeNodes = [{ id: conn.id, label: conn.name, type: "connection", connectionId: conn.id, children: [] }];
+
+ await store.loadRedisDatabases(conn.id);
+ expect(store.treeNodes[0].children).toHaveLength(3);
+
+ // 1. Set aliases for db1 and db2
+ await store.setRedisDatabaseAlias(conn.id, 1, "orders");
+ await store.setRedisDatabaseAlias(conn.id, 2, "users");
+
+ const db1Node = store.treeNodes[0].children!.find((n) => n.database === "1")!;
+ const db2Node = store.treeNodes[0].children!.find((n) => n.database === "2")!;
+ expect(db1Node.label).toBe("db1 · orders (10)");
+ expect(db2Node.label).toBe("db2 · users (20)");
+
+ // 2. Pin db2 then pin db1
+ store.toggleTreeNodePin(db2Node);
+ store.toggleTreeNodePin(db1Node);
+
+ expect(store.isTreeNodePinned(db2Node)).toBe(true);
+ expect(store.isTreeNodePinned(db1Node)).toBe(true);
+ expect(store.treeNodes[0].children!.map((n) => n.database)).toEqual(["2", "1", "0"]);
+
+ // 3. Simulate reconnect / database reload (e.g. key counts might be slightly different or same)
+ redisListDatabases.mockResolvedValue([
+ { db: 0, keys: 5 },
+ { db: 1, keys: 11 }, // count changed slightly
+ { db: 2, keys: 20 },
+ ]);
+ await store.loadRedisDatabases(conn.id);
+
+ const reloadedChildren = store.treeNodes[0].children!;
+ const reloadedDb2 = reloadedChildren.find((n) => n.database === "2")!;
+ const reloadedDb1 = reloadedChildren.find((n) => n.database === "1")!;
+ const reloadedDb0 = reloadedChildren.find((n) => n.database === "0")!;
+
+ expect(store.isTreeNodePinned(reloadedDb2)).toBe(true);
+ expect(store.isTreeNodePinned(reloadedDb1)).toBe(true);
+ expect(store.isTreeNodePinned(reloadedDb0)).toBe(false);
+ expect(reloadedChildren.map((n) => n.database)).toEqual(["2", "1", "0"]);
+
+ // 4. Unpin db2: db1 remains pinned first, db2 returns to natural order
+ store.toggleTreeNodePin(reloadedDb2);
+ expect(store.isTreeNodePinned(reloadedDb2)).toBe(false);
+ expect(store.isTreeNodePinned(reloadedDb1)).toBe(true);
+ expect(store.treeNodes[0].children!.map((n) => n.database)).toEqual(["1", "0", "2"]);
+ });
+
+ it("preserves pinned state when alias is assigned after pinning and database is reloaded", async () => {
+ const saveConnections = vi.fn().mockResolvedValue(undefined);
+ const savePinnedTreeNodeIds = vi.fn().mockResolvedValue(undefined);
+ const redisListDatabases = vi.fn().mockResolvedValue([
+ { db: 0, keys: 5 },
+ { db: 1, keys: 10 },
+ ]);
+ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
+ vi.doMock("@/lib/backend/api", () => ({
+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
+ saveConnections,
+ savePinnedTreeNodeIds,
+ redisListDatabases,
+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
+ loadSchemaCache: vi.fn().mockResolvedValue(null),
+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),
+ }));
+
+ const { useConnectionStore } = await import("@/stores/connectionStore");
+ const { useSettingsStore } = await import("@/stores/settingsStore");
+ useSettingsStore().updateEditorSettings({ sidebarPinDefaultDatabase: false });
+ const store = useConnectionStore();
+ const conn = redisConnection();
+ store.connections = [conn];
+ store.connectedIds.add(conn.id);
+ store.treeNodes = [{ id: conn.id, label: conn.name, type: "connection", connectionId: conn.id, children: [] }];
+
+ await store.loadRedisDatabases(conn.id);
+ const db1Node = store.treeNodes[0].children!.find((n) => n.database === "1")!;
+
+ // Pin db1 first without alias
+ store.toggleTreeNodePin(db1Node);
+ expect(store.isTreeNodePinned(db1Node)).toBe(true);
+
+ // Set alias for db1
+ await store.setRedisDatabaseAlias(conn.id, 1, "analytics");
+ expect(store.isTreeNodePinned(db1Node)).toBe(true);
+
+ // Reconnect / reload
+ await store.loadRedisDatabases(conn.id);
+ const reloadedDb1 = store.treeNodes[0].children!.find((n) => n.database === "1")!;
+ expect(store.isTreeNodePinned(reloadedDb1)).toBe(true);
+ expect(store.treeNodes[0].children!.map((n) => n.database)).toEqual(["1", "0"]);
+ });
});
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 0c0213bd0f..0f59530c7e 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -33,10 +33,12 @@ import type {
} from "@/types/database";
import {
inheritNaturalTreeNodeOrder,
+ isPinnedKeyPresent,
migrateLegacyPinnedTreeNodeOrder,
normalizePinnedTreeNodeOrder,
orderItemsByPinnedTreeNodeOrder,
pinnedTreeNodeIdentityMatches,
+ pinnedTreeNodeOrderKeyMatchesNode,
removePinnedTreeNodesFromOrder,
reorderPinnedTreeNodeOrder,
replacePinnedTreeNodeInOrder,
@@ -1899,10 +1901,10 @@ export const useConnectionStore = defineStore("connection", () => {
}
function isTreeNodePinned(node: TreeNode | string): boolean {
- if (typeof node !== "string") return pinnedTreeNodeIds.value.has(treeNodePinKey(node)) || pinnedTreeNodeIds.value.has(node.id);
+ if (typeof node !== "string") return isPinnedKeyPresent(node, pinnedTreeNodeIds.value);
if (pinnedTreeNodeIds.value.has(node)) return true;
const loadedNode = findLoadedTreeNodeById(treeNodes.value, node);
- return !!loadedNode && pinnedTreeNodeIds.value.has(treeNodePinKey(loadedNode));
+ return !!loadedNode && isPinnedKeyPresent(loadedNode, pinnedTreeNodeIds.value);
}
function isFixedPriorityTreeNode(node: TreeNode): boolean {
@@ -3900,12 +3902,12 @@ export const useConnectionStore = defineStore("connection", () => {
function toggleTreeNodePin(node: TreeNode) {
const pinKey = treeNodePinKey(node);
- const wasPinned = pinnedTreeNodeIds.value.has(pinKey) || pinnedTreeNodeIds.value.has(node.id);
+ const wasPinned = isPinnedKeyPresent(node, pinnedTreeNodeIds.value);
// Remove the legacy bare id as part of every toggle so old ambiguous pins
// cannot continue matching objects in a different database. Newly pinned
// nodes append to the persisted order, placing them last in their sibling
// pin section until the user explicitly reorders them.
- const next = pinnedTreeNodeOrder.value.filter((id) => id !== node.id && id !== pinKey);
+ const next = pinnedTreeNodeOrder.value.filter((id) => !pinnedTreeNodeOrderKeyMatchesNode(id, node));
if (!wasPinned) next.push(pinKey);
setPinnedTreeNodeOrder(next);
persistPinnedTreeNodeIds();