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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(redis): faithful byte escaping and bounded group deletion for danger copy preview (#12892)
lxk95541c38cb9c301
diff --git a/apps/desktop/src/components/redis/RedisKeyBrowser.expiry.spec.ts b/apps/desktop/src/components/redis/RedisKeyBrowser.expiry.spec.tsindex 3510bd04e3..4933ac1cdf 100644--- a/apps/desktop/src/components/redis/RedisKeyBrowser.expiry.spec.ts+++ b/apps/desktop/src/components/redis/RedisKeyBrowser.expiry.spec.ts@@ -1627,7 +1627,8 @@ describe("RedisKeyBrowser fuzzy key hierarchy", () => {expect(mocks.redisDeleteKeys).not.toHaveBeenCalled();expect(requiredElement<HTMLElement>("[data-test-danger-details]").textContent).toContain("MCP");- expect(requiredElement<HTMLElement>("[data-test-danger-sql]").textContent).toContain("EVAL");+ expect(requiredElement<HTMLElement>("[data-test-danger-sql]").textContent).toContain("redis-cli");+ expect(requiredElement<HTMLElement>("[data-test-danger-sql]").textContent).toContain("--scan");expect(requiredElement<HTMLElement>("[data-test-danger-sql]").textContent).toContain("MCP:*");requiredElement<HTMLButtonElement>("[data-test-danger-confirm]").click();await settle();diff --git a/apps/desktop/src/components/redis/RedisKeyBrowser.vue b/apps/desktop/src/components/redis/RedisKeyBrowser.vueindex 23be8536d7..b6869d4aae 100644--- a/apps/desktop/src/components/redis/RedisKeyBrowser.vue+++ b/apps/desktop/src/components/redis/RedisKeyBrowser.vue@@ -52,7 +52,7 @@ import {} from "@/lib/redis/redisKeyTree";import { classifyRedisCommandSafety } from "@/lib/redis/redisCommandSafety";import { isRedisMutatingCommand } from "@/lib/redis/redisCommandTable";-import { isRedisClearScreenCommand, nextRedisCommandDb, redisKeyRawToText, redisKeyTextToRaw } from "@/lib/redis/redisCommandSession";+import { isRedisClearScreenCommand, nextRedisCommandDb, redisKeyTextToRaw } from "@/lib/redis/redisCommandSession";import { buildRedisCompletionItemsFromContext, getRedisCompletionContext, takesKeyArgument, type RedisCompletionItem } from "@/lib/redis/redisCompletion";import type { RedisCommandDocumentation } from "@/lib/redis/redisCommandDocs";import { formatRedisConsoleValue, redisValuePreview, redisValueSize } from "@/lib/redis/redisValuePresentation";@@ -477,18 +477,23 @@ const dangerDetailsText = computed(() => {}return "";});-function redisKeyNameFromRaw(keyRaw: string): string {- return flatKeyByRaw.get(keyRaw)?.key_display ?? redisKeyRawToText(keyRaw) ?? keyRaw;-}++const isClusterMode = computed(() => connectionStore.getConfig(props.connectionId)?.redis_connection_mode === "cluster");const dangerSql = computed(() => {if (!pendingDanger.value) return "";if (pendingDanger.value.kind === "delete-keys") {- const keyNames = pendingDanger.value.keyRaws.map(redisKeyNameFromRaw);- return redisDeleteKeysPreview(keyNames);+ return redisDeleteKeysPreview(pendingDanger.value.keyRaws, {+ raw: true,+ database: props.db,+ isCluster: isClusterMode.value,+ });}if (pendingDanger.value.kind === "delete-group") {- return redisDeleteGroupPreview(pendingDanger.value.pattern);+ return redisDeleteGroupPreview(pendingDanger.value.pattern, {+ database: props.db,+ isCluster: isClusterMode.value,+ });}return pendingDanger.value.command;});diff --git a/apps/desktop/src/components/redis/RedisValueViewer.vue b/apps/desktop/src/components/redis/RedisValueViewer.vueindex 02f3320922..0f572c2612 100644--- a/apps/desktop/src/components/redis/RedisValueViewer.vue+++ b/apps/desktop/src/components/redis/RedisValueViewer.vue@@ -24,6 +24,7 @@ import { startRedisContentSearch } from "@/lib/redis/redisContentSearchJob";import JsonTree from "@/components/common/JsonTree.vue";import RedisJsonEditor from "@/components/redis/RedisJsonEditor.vue";import * as api from "@/lib/backend/api";+import { useConnectionStore } from "@/stores/connectionStore";import type { RedisBlob, RedisHashItem, RedisKeyInfo, RedisListItem, RedisSetItem, RedisStreamConsumer, RedisStreamEntry, RedisStreamGroup, RedisStreamPendingEntry, RedisValue, RedisZsetItem } from "@/lib/backend/api";import { useToast } from "@/composables/useToast";import { useTheme } from "@/composables/useTheme";@@ -998,7 +999,10 @@ function shouldPauseAutoValueRefresh(): boolean {return showMemberDetail.value || editingZsetMemberKey.value !== null || showHashFieldTtlDialog.value || valueSearchOpen.value || Boolean(collectionSearchQuery.value.trim()) || Boolean(activeCollectionSearchQuery.value) || searchLoading.value || loadingMore.value || hasExpandedCollectionPage;}-type PendingDelete = { kind: "key" } | { kind: "hash"; field: string } | { kind: "list"; index: number } | { kind: "set"; member: string } | { kind: "zset"; member: string };+const connectionStore = useConnectionStore();+const isClusterMode = computed(() => connectionStore.getConfig(props.connectionId)?.redis_connection_mode === "cluster");++type PendingDelete = { kind: "key" } | { kind: "hash"; field: RedisBlob | string } | { kind: "list"; index: number } | { kind: "set"; member: RedisBlob | string } | { kind: "zset"; member: RedisBlob | string };const pendingDelete = ref<PendingDelete | null>(null);type RedisMemberContext =@@ -1772,7 +1776,11 @@ const deleteDetailsText = computed(() => {const deleteSql = computed(() => {const pending = pendingDelete.value;if (!pending) return "";- return redisDeleteValueItemPreview(props.keyDisplay || props.keyRaw, pending);+ return redisDeleteValueItemPreview(props.keyRaw, pending, {+ raw: true,+ database: props.db,+ isCluster: isClusterMode.value,+ });});async function load(options: { background?: boolean; notifyParent?: boolean; preserveDraft?: boolean; selectDefaultMember?: boolean; shouldApply?: () => boolean } = {}): Promise<boolean> {@@ -2545,19 +2553,19 @@ function resolveSelectedMember(context: RedisMemberContext): { title: string; va}}-function requestHashDel(field: string | null) {+function requestHashDel(field: RedisBlob | string | null) {if (!field) return;pendingDelete.value = { kind: "hash", field };showDeleteConfirm.value = true;}-function requestSetRemove(member: string | null) {+function requestSetRemove(member: RedisBlob | string | null) {if (!member) return;pendingDelete.value = { kind: "set", member };showDeleteConfirm.value = true;}-function requestZsetRemove(member: string | null) {+function requestZsetRemove(member: RedisBlob | string | null) {if (!member) return;pendingDelete.value = { kind: "zset", member };showDeleteConfirm.value = true;@@ -2810,14 +2818,19 @@ async function applyZsetRemove(member: string) {await load();}+function extractMemberText(val: RedisBlob | string): string {+ if (typeof val === "string") return val;+ return redisBlobText(val) ?? "";+}+async function confirmDelete() {const pending = pendingDelete.value;if (!pending) return;if (pending.kind === "key") await applyDeleteKey();- else if (pending.kind === "hash") await applyHashDel(pending.field);+ else if (pending.kind === "hash") await applyHashDel(extractMemberText(pending.field));else if (pending.kind === "list") await applyListRemove(pending.index);- else if (pending.kind === "set") await applySetRemove(pending.member);- else if (pending.kind === "zset") await applyZsetRemove(pending.member);+ else if (pending.kind === "set") await applySetRemove(extractMemberText(pending.member));+ else if (pending.kind === "zset") await applyZsetRemove(extractMemberText(pending.member));pendingDelete.value = null;}@@ -3411,7 +3424,7 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving><Eye class="w-3 h-3"/></Button><Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100" :title="t('redis.copyMember')" @click.stop="copyMember(row.value.member)"><Copy class="w-3 h-3" /></Button>- <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive" :disabled="!canDeleteSetItem(row.value)" @click.stop="requestSetRemove(redisBlobText(row.value.member))"><Trash2 class="w-3 h-3" /></Button>+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive" :disabled="!canDeleteSetItem(row.value)" @click.stop="requestSetRemove(row.value.member)"><Trash2 class="w-3 h-3" /></Button></div></div></template>@@ -3500,7 +3513,7 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving</DropdownMenuContent></DropdownMenu></div>- <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive" :disabled="!canDeleteHashItem(row.value)" @click.stop="requestHashDel(redisBlobText(row.value.field))"><Trash2 class="w-3 h-3" /></Button>+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive" :disabled="!canDeleteHashItem(row.value)" @click.stop="requestHashDel(row.value.field)"><Trash2 class="w-3 h-3" /></Button></div></div></template>@@ -3574,7 +3587,7 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving><Pencil class="w-3 h-3"/></Button><Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100" :title="t('redis.copyMember')" @click="copyMember(row.value.member)"><Copy class="w-3 h-3" /></Button>- <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive" :disabled="!canDeleteZsetItem(row.value)" @click="requestZsetRemove(redisBlobText(row.value.member))"><Trash2 class="w-3 h-3" /></Button>+ <Button variant="ghost" size="icon" class="h-5 w-5 opacity-0 group-hover:opacity-100 text-destructive" :disabled="!canDeleteZsetItem(row.value)" @click="requestZsetRemove(row.value.member)"><Trash2 class="w-3 h-3" /></Button></template></div></div>diff --git a/apps/desktop/src/components/redis/__tests__/RedisDangerCommandPreview.spec.ts b/apps/desktop/src/components/redis/__tests__/RedisDangerCommandPreview.spec.tsindex 713a7d47d2..20592b0466 100644--- a/apps/desktop/src/components/redis/__tests__/RedisDangerCommandPreview.spec.ts+++ b/apps/desktop/src/components/redis/__tests__/RedisDangerCommandPreview.spec.ts@@ -96,9 +96,9 @@ describe("Redis DangerConfirmDialog copy command behavior (issue #12892)", () =>expect(copyToClipboard).toHaveBeenCalledWith('DEL user:1 user:2 "cache:session with space"');});- it("copies EVAL script when deleting a group instead of subtree description text", async () => {+ it("copies bounded scan-and-delete command when deleting a group instead of EVAL", async () => {const pattern = "app:cache:*";- const sql = redisDeleteGroupPreview(pattern);+ const sql = redisDeleteGroupPreview(pattern, { database: 2 });const detailsText = "app:cache\n将删除该分组下的全部 key(已加载 10 个)";await mountDangerDialog({@@ -109,19 +109,23 @@ describe("Redis DangerConfirmDialog copy command behavior (issue #12892)", () =>});const codeContainer = document.body.querySelector('[data-testid="danger-code-container"]');- expect(codeContainer?.textContent).toContain("EVAL");- expect(codeContainer?.textContent).toContain("app:cache:*");+ expect(codeContainer?.textContent).toContain("redis-cli");+ expect(codeContainer?.textContent).toContain("--scan");+ expect(codeContainer?.textContent).toContain('"app:cache:*"');+ expect(codeContainer?.textContent).toContain("xargs -L 512");+ expect(codeContainer?.textContent).not.toContain("EVAL");const copyBtn = document.body.querySelector<HTMLButtonElement>('[data-testid="danger-code-actions"] button');copyBtn?.click();await nextTick();- expect(copyToClipboard).toHaveBeenCalledWith("EVAL \"local keys = redis.call('keys', ARGV[1]) for _, k in ipairs(keys) do redis.call('del', k) end return #keys\" 0 app:cache:*");+ expect(copyToClipboard).toHaveBeenCalledWith(sql);});- it("copies HDEL command when deleting a hash field in RedisValueViewer", async () => {- const sql = redisDeleteValueItemPreview("user:profile", { kind: "hash", field: "email" });- const detailsText = "Redis key:user:profile\nField: email";+ it("copies HDEL command with byte-accurate escaping when deleting a hash field in RedisValueViewer", async () => {+ const binaryBlob = { raw_base64: btoa("data\x00\xff"), encoding: "binary" };+ const sql = redisDeleteValueItemPreview("user\\profile", { kind: "hash", field: binaryBlob }, { database: 3 });+ const detailsText = "Redis key:user\\profile\nField: data";await mountDangerDialog({title: "删除确认",@@ -131,13 +135,14 @@ describe("Redis DangerConfirmDialog copy command behavior (issue #12892)", () =>});const codeContainer = document.body.querySelector('[data-testid="danger-code-container"]');- expect(codeContainer?.textContent).toContain("HDEL user:profile email");+ expect(codeContainer?.textContent).toContain("SELECT 3");+ expect(codeContainer?.textContent).toContain('HDEL "user\\\\profile" "data\\x00\\xff"');const copyBtn = document.body.querySelector<HTMLButtonElement>('[data-testid="danger-code-actions"] button');copyBtn?.click();await nextTick();- expect(copyToClipboard).toHaveBeenCalledWith("HDEL user:profile email");+ expect(copyToClipboard).toHaveBeenCalledWith('SELECT 3\nHDEL "user\\\\profile" "data\\x00\\xff"');});it("copies SREM command when deleting a set member in RedisValueViewer", async () => {@@ -151,6 +156,9 @@ describe("Redis DangerConfirmDialog copy command behavior (issue #12892)", () =>sql,});+ const codeContainer = document.body.querySelector('[data-testid="danger-code-container"]');+ expect(codeContainer?.textContent).toContain("SREM tags:article news");+const copyBtn = document.body.querySelector<HTMLButtonElement>('[data-testid="danger-code-actions"] button');copyBtn?.click();await nextTick();@@ -169,6 +177,9 @@ describe("Redis DangerConfirmDialog copy command behavior (issue #12892)", () =>sql,});+ const codeContainer = document.body.querySelector('[data-testid="danger-code-container"]');+ expect(codeContainer?.textContent).toContain("ZREM leaderboard player1");+const copyBtn = document.body.querySelector<HTMLButtonElement>('[data-testid="danger-code-actions"] button');copyBtn?.click();await nextTick();diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vueindex 96e4eae1d4..464a6d6fff 100644--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue@@ -6305,11 +6305,13 @@ routeDangerDialog(showClearElasticsearchIndexConfirm, () => {routeDangerDialog(showFlushRedisDbConfirm, () => {const node = sidebarDangerTarget.value ?? activeNode.value;+ const connectionId = node.connectionId ?? activeNode.value.connectionId;+ const isCluster = connectionId ? connectionStore.getConfig(connectionId)?.redis_connection_mode === "cluster" : false;return dangerRequest({title: t("redis.flushDb"),message: t("redis.flushDbMessage"),detailsText: t("redis.flushDbDetails", { db: node.database ?? "" }),- sql: redisFlushDbPreview(node.database),+ sql: redisFlushDbPreview(node.database, isCluster),confirmLabel: t("redis.flushDbConfirm"),confirm: confirmFlushRedisDb,});diff --git a/apps/desktop/src/lib/redis/__tests__/redisCommandPreview.spec.ts b/apps/desktop/src/lib/redis/__tests__/redisCommandPreview.spec.tsindex f0a3c81cbc..3cc99ca3a7 100644--- a/apps/desktop/src/lib/redis/__tests__/redisCommandPreview.spec.ts+++ b/apps/desktop/src/lib/redis/__tests__/redisCommandPreview.spec.ts@@ -1,9 +1,11 @@import { describe, expect, it } from "vitest";-import { quoteRedisArg, redisFlushDbPreview, redisDeleteKeysPreview, redisDeleteGroupPreview, redisDeleteValueItemPreview } from "../redisCommandPreview";+import { base64ToBytes, quoteRedisArg, quoteRedisBytes, quoteRedisKeyRaw, redisDeleteGroupPreview, redisDeleteKeysPreview, redisDeleteValueItemPreview, redisFlushDbPreview } from "../redisCommandPreview";+import { redisKeyTextToRaw } from "../redisCommandSession";-describe("quoteRedisArg", () => {+describe("quoteRedisArg and quoteRedisBytes", () => {it("quotes empty string", () => {expect(quoteRedisArg("")).toBe('""');+ expect(quoteRedisBytes(new Uint8Array([]))).toBe('""');});it("leaves simple keys unquoted", () => {@@ -18,28 +20,60 @@ describe("quoteRedisArg", () => {expect(quoteRedisArg("key\nwith\nnewline")).toBe('"key\\nwith\\nnewline"');});- it("quotes keys with quotes or backslashes", () => {+ it("quotes keys with quotes or backslashes with exact single-escaping", () => {expect(quoteRedisArg('key"with"doublequote')).toBe('"key\\"with\\"doublequote"');expect(quoteRedisArg("key'with'singlequote")).toBe("\"key'with'singlequote\"");expect(quoteRedisArg("key\\with\\backslash")).toBe('"key\\\\with\\\\backslash"');});++ it("quotes binary bytes and control characters with \\xHH", () => {+ const binaryBytes = new Uint8Array([0x00, 0x01, 0x1f, 0x7f, 0xff]);+ expect(quoteRedisBytes(binaryBytes)).toBe('"\\x00\\x01\\x1f\\x7f\\xff"');+ });++ it("preserves valid UTF-8 sequences verbatim inside quotes", () => {+ expect(quoteRedisArg("用户:123:设置")).toBe('"用户:123:设置"');+ });++ it("quotes RedisBlob objects using raw_base64 bytes", () => {+ const utf8Blob = { raw_base64: btoa("hello world"), encoding: "utf8" };+ expect(quoteRedisArg(utf8Blob)).toBe('"hello world"');++ const binaryBlob = { raw_base64: btoa("\x00\xff"), encoding: "binary" };+ expect(quoteRedisArg(binaryBlob)).toBe('"\\x00\\xff"');+ });+});++describe("quoteRedisKeyRaw", () => {+ it("recovers exact bytes from key_raw without double backslash escaping", () => {+ const rawWithBackslash = redisKeyTextToRaw("cache\\session");+ expect(quoteRedisKeyRaw(rawWithBackslash)).toBe('"cache\\\\session"');+ });++ it("quotes binary key_raw containing null bytes and high bytes", () => {+ const binaryRaw = btoa("k\x00\xff");+ expect(quoteRedisKeyRaw(binaryRaw)).toBe('"k\\x00\\xff"');+ });});describe("redisFlushDbPreview", () => {- it("prefixes with SELECT when database is provided", () => {+ it("prefixes with SELECT in standalone mode when database is provided", () => {expect(redisFlushDbPreview(6)).toBe("SELECT 6\nFLUSHDB");expect(redisFlushDbPreview("6")).toBe("SELECT 6\nFLUSHDB");expect(redisFlushDbPreview("db6")).toBe("SELECT 6\nFLUSHDB");expect(redisFlushDbPreview(0)).toBe("SELECT 0\nFLUSHDB");expect(redisFlushDbPreview("0")).toBe("SELECT 0\nFLUSHDB");- expect(redisFlushDbPreview("db0")).toBe("SELECT 0\nFLUSHDB");});it("returns FLUSHDB when database is absent or empty", () => {expect(redisFlushDbPreview(undefined)).toBe("FLUSHDB");expect(redisFlushDbPreview(null)).toBe("FLUSHDB");expect(redisFlushDbPreview("")).toBe("FLUSHDB");- expect(redisFlushDbPreview(" ")).toBe("FLUSHDB");+ });++ it("omits SELECT in Cluster mode because Cluster does not allow SELECT", () => {+ expect(redisFlushDbPreview(6, true)).toBe("FLUSHDB");+ expect(redisFlushDbPreview("db3", true)).toBe("FLUSHDB");});});@@ -48,14 +82,9 @@ describe("redisDeleteKeysPreview", () => {expect(redisDeleteKeysPreview([])).toBe("");});- it("formats single key deletion", () => {+ it("formats single and multiple keys", () => {expect(redisDeleteKeysPreview(["user:1"])).toBe("DEL user:1");- expect(redisDeleteKeysPreview(["key with space"])).toBe('DEL "key with space"');- });-- it("formats multiple key deletions on a single line within chunkSize", () => {- const keys = ["k1", "k2", "k3", "k4 with space"];- expect(redisDeleteKeysPreview(keys)).toBe('DEL k1 k2 k3 "k4 with space"');+ expect(redisDeleteKeysPreview(["user:1", "user:2", "cache:session with space"])).toBe('DEL user:1 user:2 "cache:session with space"');});it("chunks large key lists across multiple DEL lines", () => {@@ -63,32 +92,63 @@ describe("redisDeleteKeysPreview", () => {const preview = redisDeleteKeysPreview(keys, 3);expect(preview).toBe("DEL key:1 key:2 key:3\nDEL key:4 key:5 key:6\nDEL key:7");});++ it("handles base64 key_raw directly with raw: true", () => {+ const keyRaws = [redisKeyTextToRaw("user:1"), redisKeyTextToRaw("path\\to\\key"), btoa("bin\x00key")];+ const preview = redisDeleteKeysPreview(keyRaws, { raw: true });+ expect(preview).toBe('DEL user:1 "path\\\\to\\\\key" "bin\\x00key"');+ });++ it("prefixes SELECT for non-zero database in standalone mode", () => {+ const keys = ["k1", "k2"];+ expect(redisDeleteKeysPreview(keys, { database: 3 })).toBe("SELECT 3\nDEL k1 k2");+ expect(redisDeleteKeysPreview(keys, { database: 0 })).toBe("DEL k1 k2");+ expect(redisDeleteKeysPreview(keys, { database: 3, isCluster: true })).toBe("DEL k1 k2");+ });});describe("redisDeleteGroupPreview", () => {- it("formats EVAL command with pattern parameter", () => {- expect(redisDeleteGroupPreview("user:*")).toBe("EVAL \"local keys = redis.call('keys', ARGV[1]) for _, k in ipairs(keys) do redis.call('del', k) end return #keys\" 0 user:*");+ it("formats bounded standalone scan-and-delete command with batch limit 512", () => {+ const preview = redisDeleteGroupPreview("user:*");+ expect(preview).toContain("# Applicable: Standalone Redis");+ expect(preview).toContain("SCAN COUNT 500, DEL in batches of up to 512 keys");+ expect(preview).toContain('redis-cli --scan --pattern "user:*" | xargs -L 512 redis-cli DEL');+ expect(preview).not.toContain("EVAL");+ });++ it("includes -n <db> for non-zero database in standalone mode", () => {+ const preview = redisDeleteGroupPreview("user:*", { database: 2 });+ expect(preview).toContain("# Applicable: Standalone Redis (db 2)");+ expect(preview).toContain('redis-cli -n 2 --scan --pattern "user:*" | xargs -L 512 redis-cli -n 2 DEL');});- it("quotes pattern if it contains whitespace", () => {- expect(redisDeleteGroupPreview("group with space:*")).toBe("EVAL \"local keys = redis.call('keys', ARGV[1]) for _, k in ipairs(keys) do redis.call('del', k) end return #keys\" 0 \"group with space:*\"");+ it("formats cluster preview with per-node execution documentation and avoids cross-slot EVAL", () => {+ const preview = redisDeleteGroupPreview("cache:*", { isCluster: true });+ expect(preview).toContain("# Applicable: Redis Cluster (per-node execution)");+ expect(preview).toContain("Cross-slot");+ expect(preview).toContain('redis-cli -h <node-host> -p <node-port> --scan --pattern "cache:*" | xargs -L 512 redis-cli -h <node-host> -p <node-port> DEL');+ expect(preview).not.toContain("EVAL");});});describe("redisDeleteValueItemPreview", () => {it("formats key deletion", () => {expect(redisDeleteValueItemPreview("user:100", { kind: "key" })).toBe("DEL user:100");- expect(redisDeleteValueItemPreview("key with space", { kind: "key" })).toBe('DEL "key with space"');});- it("formats hash field deletion", () => {+ it("formats hash field deletion with raw bytes and special characters", () => {expect(redisDeleteValueItemPreview("user:100", { kind: "hash", field: "email" })).toBe("HDEL user:100 email");- expect(redisDeleteValueItemPreview("user:100", { kind: "hash", field: "full name" })).toBe('HDEL user:100 "full name"');+ expect(redisDeleteValueItemPreview("user:100", { kind: "hash", field: "path\\field" })).toBe('HDEL user:100 "path\\\\field"');++ const binaryBlob = { raw_base64: btoa("\x00\x01\xff"), encoding: "binary" };+ expect(redisDeleteValueItemPreview("user:100", { kind: "hash", field: binaryBlob })).toBe('HDEL user:100 "\\x00\\x01\\xff"');});- it("formats set member deletion", () => {+ it("formats set member deletion with raw bytes and special characters", () => {expect(redisDeleteValueItemPreview("tags", { kind: "set", member: "vip" })).toBe("SREM tags vip");- expect(redisDeleteValueItemPreview("tags", { kind: "set", member: "top customer" })).toBe('SREM tags "top customer"');++ const binaryBlob = { raw_base64: btoa("sub\x00member"), encoding: "binary" };+ expect(redisDeleteValueItemPreview("tags", { kind: "set", member: binaryBlob })).toBe('SREM tags "sub\\x00member"');});it("formats zset member deletion", () => {@@ -98,4 +158,16 @@ describe("redisDeleteValueItemPreview", () => {it("formats list index removal", () => {expect(redisDeleteValueItemPreview("queue", { kind: "list", index: 2 })).toBe('LSET queue 2 "__DELETED_PLACEHOLDER__"\nLREM queue 1 "__DELETED_PLACEHOLDER__"');});++ it("respects raw key and non-zero database options", () => {+ const rawKey = redisKeyTextToRaw("user\\name");+ const preview = redisDeleteValueItemPreview(rawKey, { kind: "hash", field: "attr" }, { raw: true, database: 4 });+ expect(preview).toBe('SELECT 4\nHDEL "user\\\\name" attr');+ });++ it("omits SELECT in Cluster mode", () => {+ const rawKey = redisKeyTextToRaw("user\\name");+ const preview = redisDeleteValueItemPreview(rawKey, { kind: "hash", field: "attr" }, { raw: true, database: 4, isCluster: true });+ expect(preview).toBe('HDEL "user\\\\name" attr');+ });});diff --git a/apps/desktop/src/lib/redis/redisCommandPreview.ts b/apps/desktop/src/lib/redis/redisCommandPreview.tsindex 083ceb8d50..bcdde3f410 100644--- a/apps/desktop/src/lib/redis/redisCommandPreview.ts+++ b/apps/desktop/src/lib/redis/redisCommandPreview.ts@@ -3,25 +3,183 @@* in DangerConfirmDialog and related confirmation prompts.*/+export interface RedisBlobLike {+ raw_base64: string;+ encoding?: string;+}+export type RedisValuePendingDelete = { kind: "key" } | { kind: "hash"; field: unknown } | { kind: "list"; index: number } | { kind: "set"; member: unknown } | { kind: "zset"; member: unknown };+export interface RedisDeleteKeysOptions {+ database?: string | number | null;+ isCluster?: boolean;+ chunkSize?: number;+ /**+ * If true, string keys are treated as base64-encoded `key_raw`.+ * Otherwise, string keys are treated as regular UTF-8 key strings.+ */+ raw?: boolean;+}++export interface RedisDeleteGroupOptions {+ database?: string | number | null;+ isCluster?: boolean;+}++export interface RedisDeleteValueItemOptions {+ database?: string | number | null;+ isCluster?: boolean;+ /**+ * If true, string `key` is treated as base64-encoded `key_raw`.+ */+ raw?: boolean;+}++/**+ * Decodes a Base64 string into raw bytes.+ */+export function base64ToBytes(base64: string): Uint8Array {+ const binary = atob(base64);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) {+ bytes[i] = binary.charCodeAt(i);+ }+ return bytes;+}++/**+ * Serializes raw byte buffer into an executable Redis argument token.+ * Safe ASCII characters (alphanumeric, `:`, `_`, `-`, `.`, `/`, etc.) are emitted unquoted.+ * Arguments containing whitespace, quotes, backslashes, or control/binary bytes are wrapped+ * in double quotes with standard Redis escaping (`\"`, `\\`, `\n`, `\r`, `\t`, `\xHH`).+ */+export function quoteRedisBytes(bytes: Uint8Array): string {+ if (bytes.length === 0) return '""';++ let canBeUnquoted = true;+ for (let i = 0; i < bytes.length; i++) {+ const b = bytes[i]!;+ const isSafe =+ (b >= 48 && b <= 57) || // 0-9+ (b >= 65 && b <= 90) || // A-Z+ (b >= 97 && b <= 122) || // a-z+ b === 95 || // _+ b === 45 || // -+ b === 58 || // :+ b === 46 || // .+ b === 47 || // /+ b === 64 || // @+ b === 43 || // ++ b === 126 || // ~+ b === 37; // %+ if (!isSafe) {+ canBeUnquoted = false;+ break;+ }+ }++ if (canBeUnquoted) {+ return new TextDecoder().decode(bytes);+ }++ let result = '"';+ const utf8Decoder = new TextDecoder("utf-8", { fatal: true });++ for (let i = 0; i < bytes.length; i++) {+ const b = bytes[i]!;++ if (b === 0x22) {+ result += '\\"';+ } else if (b === 0x5c) {+ result += "\\\\";+ } else if (b === 0x0a) {+ result += "\\n";+ } else if (b === 0x0d) {+ result += "\\r";+ } else if (b === 0x09) {+ result += "\\t";+ } else if (b === 0x07) {+ result += "\\a";+ } else if (b === 0x08) {+ result += "\\b";+ } else if (b >= 0x20 && b <= 0x7e) {+ result += String.fromCharCode(b);+ } else if (b >= 0x80) {+ // Check if this byte starts a valid UTF-8 character sequence+ let decodedChar: string | null = null;+ let matchedLen = 0;+ for (let len = 4; len >= 2; len--) {+ if (i + len <= bytes.length) {+ try {+ const candidate = utf8Decoder.decode(bytes.subarray(i, i + len));+ // Ensure no C1 control characters (U+0080 to U+009F)+ if (!/[\u0080-\u009f]/.test(candidate)) {+ decodedChar = candidate;+ matchedLen = len;+ break;+ }+ } catch {+ // Not a valid UTF-8 sequence of this length+ }+ }+ }++ if (decodedChar !== null && matchedLen > 0) {+ result += decodedChar;+ i += matchedLen - 1;+ } else {+ result += "\\x" + b.toString(16).padStart(2, "0");+ }+ } else {+ // Control character < 0x20 or 0x7f+ result += "\\x" + b.toString(16).padStart(2, "0");+ }+ }++ result += '"';+ return result;+}+/**- * Quotes an argument for Redis command execution if it contains spaces,- * quotes, backslashes, control characters, or is empty.+ * Quotes a key given by its base64 `key_raw` string representation.*/-export function quoteRedisArg(arg: string): string {- if (arg.length === 0) return '""';- if (/[\s"'\\]/.test(arg)) {- return JSON.stringify(arg);+export function quoteRedisKeyRaw(keyRaw: string): string {+ try {+ const bytes = base64ToBytes(keyRaw);+ return quoteRedisBytes(bytes);+ } catch {+ return quoteRedisArg(keyRaw);}- return arg;+}++/**+ * Quotes an arbitrary Redis command argument (string, Uint8Array, RedisBlob, number).+ */+export function quoteRedisArg(arg: unknown): string {+ if (arg == null) return '""';+ if (arg instanceof Uint8Array) {+ return quoteRedisBytes(arg);+ }+ if (typeof arg === "object" && "raw_base64" in arg && typeof (arg as RedisBlobLike).raw_base64 === "string") {+ return quoteRedisKeyRaw((arg as RedisBlobLike).raw_base64);+ }+ if (typeof arg === "number") {+ return String(arg);+ }+ const str = String(arg);+ const bytes = new TextEncoder().encode(str);+ return quoteRedisBytes(bytes);}/*** Returns the command preview for flushing a Redis database.- * If database is provided, prefixes with `SELECT <db>`.+ * If database is provided and not Cluster mode, prefixes with `SELECT <db>`.+ * In Cluster mode, `SELECT` is not supported and is omitted.*/-export function redisFlushDbPreview(database?: string | number | null): string {+export function redisFlushDbPreview(database?: string | number | null, isCluster = false): string {+ if (isCluster) {+ return "FLUSHDB";+ }if (database != null && String(database).trim() !== "") {const dbIndex = String(database).trim().replace(/^db/i, "");return `SELECT ${dbIndex}\nFLUSHDB`;@@ -32,34 +190,108 @@ export function redisFlushDbPreview(database?: string | number | null): string {/*** Formats a list of Redis keys into `DEL` commands.* If keys exceed chunkSize, chunks them across multiple `DEL` lines.+ * In standalone mode with a non-zero database, prefixes with `SELECT <db>`.*/-export function redisDeleteKeysPreview(keys: readonly string[], chunkSize = 50): string {+export function redisDeleteKeysPreview(keys: readonly (string | Uint8Array)[], options?: RedisDeleteKeysOptions | number): string {if (keys.length === 0) return "";- const quoted = keys.map(quoteRedisArg);++ const opts: RedisDeleteKeysOptions = typeof options === "number" ? { chunkSize: options } : (options ?? {});+ const chunkSize = Math.max(1, opts.chunkSize ?? 512);+ const isCluster = opts.isCluster ?? false;+ const isRaw = opts.raw ?? false;++ const quoted = keys.map((key) => {+ if (key instanceof Uint8Array) return quoteRedisBytes(key);+ if (isRaw) return quoteRedisKeyRaw(key);+ return quoteRedisArg(key);+ });+const lines: string[] = [];- const size = Math.max(1, chunkSize);- for (let i = 0; i < quoted.length; i += size) {- lines.push(`DEL ${quoted.slice(i, i + size).join(" ")}`);+ if (!isCluster && opts.database != null && String(opts.database).trim() !== "") {+ const dbIndex = Number(String(opts.database).trim().replace(/^db/i, ""));+ if (Number.isFinite(dbIndex) && dbIndex > 0) {+ lines.push(`SELECT ${dbIndex}`);+ }}++ for (let i = 0; i < quoted.length; i += chunkSize) {+ lines.push(`DEL ${quoted.slice(i, i + chunkSize).join(" ")}`);+ }+return lines.join("\n");}/**- * Formats a pattern deletion preview into the standard server-side Lua EVAL command.+ * Formats a pattern deletion preview into a bounded, non-blocking command scheme+ * matching the backend `delete_keys_by_pattern` executor (SCAN COUNT 500, DEL in batches <= 512).+ * Clarifies execution context between Standalone Redis and Redis Cluster.*/-export function redisDeleteGroupPreview(pattern: string): string {- const quoted = quoteRedisArg(pattern);- return `EVAL "local keys = redis.call('keys', ARGV[1]) for _, k in ipairs(keys) do redis.call('del', k) end return #keys" 0 ${quoted}`;+export function redisDeleteGroupPreview(pattern: string, options?: RedisDeleteGroupOptions): string {+ const isCluster = options?.isCluster ?? false;+ const quotedPattern = quoteRedisArg(pattern);+ const patternArg = quotedPattern.startsWith('"') ? quotedPattern : `"${pattern}"`;++ if (isCluster) {+ return [+ "# Applicable: Redis Cluster (per-node execution)",+ "# Keys matching pattern are partitioned across hash slots on different master nodes.",+ "# Cross-slot multi-key operations (CROSSSLOT) and global scripts are rejected in Cluster mode.",+ "# DBX executes delete_keys_by_pattern by scanning each master node (SCAN COUNT 500) and deleting keys in batches of up to 512 keys.",+ "# To execute manually, run against each master node:",+ `# redis-cli -h <node-host> -p <node-port> --scan --pattern ${patternArg} | xargs -L 512 redis-cli -h <node-host> -p <node-port> DEL`,+ ].join("\n");+ }++ let dbFlag = "";+ let dbLabel = "Standalone Redis";+ if (options?.database != null && String(options.database).trim() !== "") {+ const dbIndex = Number(String(options.database).trim().replace(/^db/i, ""));+ if (Number.isFinite(dbIndex) && dbIndex > 0) {+ dbFlag = ` -n ${dbIndex}`;+ dbLabel = `Standalone Redis (db ${dbIndex})`;+ }+ }++ return [`# Applicable: ${dbLabel}`, "# Matches DBX delete_keys_by_pattern: SCAN COUNT 500, DEL in batches of up to 512 keys", `redis-cli${dbFlag} --scan --pattern ${patternArg} | xargs -L 512 redis-cli${dbFlag} DEL`].join("\n");}/*** Formats a single item or key deletion within RedisValueViewer into an executable command.+ * Faithfully serializes raw bytes of keys and collection fields/members.+ * In standalone mode with a non-zero database, prefixes with `SELECT <db>`.*/-export function redisDeleteValueItemPreview(keyName: string, pending: RedisValuePendingDelete): string {- const key = quoteRedisArg(keyName);- if (pending.kind === "key") return `DEL ${key}`;- if (pending.kind === "hash") return `HDEL ${key} ${quoteRedisArg(String(pending.field ?? ""))}`;- if (pending.kind === "list") return `LSET ${key} ${pending.index} "__DELETED_PLACEHOLDER__"\nLREM ${key} 1 "__DELETED_PLACEHOLDER__"`;- if (pending.kind === "zset") return `ZREM ${key} ${quoteRedisArg(String(pending.member ?? ""))}`;- return `SREM ${key} ${quoteRedisArg(String(pending.member ?? ""))}`;+export function redisDeleteValueItemPreview(key: string | Uint8Array, pending: RedisValuePendingDelete, options?: RedisDeleteValueItemOptions): string {+ const isCluster = options?.isCluster ?? false;+ const isRaw = options?.raw ?? false;++ let quotedKey: string;+ if (key instanceof Uint8Array) {+ quotedKey = quoteRedisBytes(key);+ } else if (isRaw) {+ quotedKey = quoteRedisKeyRaw(key);+ } else {+ quotedKey = quoteRedisArg(key);+ }++ const lines: string[] = [];+ if (!isCluster && options?.database != null && String(options.database).trim() !== "") {+ const dbIndex = Number(String(options.database).trim().replace(/^db/i, ""));+ if (Number.isFinite(dbIndex) && dbIndex > 0) {+ lines.push(`SELECT ${dbIndex}`);+ }+ }++ if (pending.kind === "key") {+ lines.push(`DEL ${quotedKey}`);+ } else if (pending.kind === "hash") {+ lines.push(`HDEL ${quotedKey} ${quoteRedisArg(pending.field)}`);+ } else if (pending.kind === "list") {+ lines.push(`LSET ${quotedKey} ${pending.index} "__DELETED_PLACEHOLDER__"\nLREM ${quotedKey} 1 "__DELETED_PLACEHOLDER__"`);+ } else if (pending.kind === "zset") {+ lines.push(`ZREM ${quotedKey} ${quoteRedisArg(pending.member)}`);+ } else {+ lines.push(`SREM ${quotedKey} ${quoteRedisArg(pending.member)}`);+ }++ return lines.join("\n");}diff --git a/apps/desktop/src/lib/redis/redisCommandTokenizer.ts b/apps/desktop/src/lib/redis/redisCommandTokenizer.tsindex d8f8dcbc72..6cf2f65332 100644--- a/apps/desktop/src/lib/redis/redisCommandTokenizer.ts+++ b/apps/desktop/src/lib/redis/redisCommandTokenizer.ts@@ -22,7 +22,7 @@ export function isRedisCommentLine(line: string): boolean {}function escapedCharacter(value: string): string {- return value === "n" ? "\n" : value === "r" ? "\r" : value === "t" ? "\t" : value;+ return value === "n" ? "\n" : value === "r" ? "\r" : value === "t" ? "\t" : value === "a" ? "\x07" : value === "b" ? "\x08" : value;}export function tokenizeRedisLine(line: string): RedisArgvResult {@@ -53,6 +53,15 @@ export function tokenizeRedisLine(line: string): RedisArgvResult {}if (escaping) {+ if (character === "x" && index + 2 < end) {+ const hex = line.slice(index + 1, index + 3);+ if (/^[0-9a-fA-F]{2}$/.test(hex)) {+ value += String.fromCharCode(parseInt(hex, 16));+ index += 2;+ escaping = false;+ continue;+ }+ }value += escapedCharacter(character);escaping = false;continue;diff --git a/crates/dbx-driver-redis/src/lib.rs b/crates/dbx-driver-redis/src/lib.rsindex 837658edd7..78b96d1147 100644--- a/crates/dbx-driver-redis/src/lib.rs+++ b/crates/dbx-driver-redis/src/lib.rs@@ -2575,12 +2575,36 @@ pub fn parse_command_argv(command_text: &str) -> Result<Vec<String>, String> {while let Some(ch) = chars.next() {if escaping {token_started = true;- current.push(match ch {- 'n' => '\n',- 'r' => '\r',- 't' => '\t',- other => other,- });+ if ch == 'x' {+ let hex1 = chars.peek().copied();+ if let Some(h1) = hex1 {+ if h1.is_ascii_hexdigit() {+ chars.next();+ let hex2 = chars.peek().copied();+ if let Some(h2) = hex2 {+ if h2.is_ascii_hexdigit() {+ chars.next();+ let byte = u8::from_str_radix(&format!("{h1}{h2}"), 16).unwrap();+ current.push(byte as char);+ escaping = false;+ continue;+ }+ }+ }+ }+ current.push('x');+ } else {+ current.push(match ch {+ 'n' => '\n',+ 'r' => '\r',+ 't' => '\t',+ 'a' => '\x07',+ 'b' => '\x08',+ 'f' => '\x0c',+ 'v' => '\x0b',+ other => other,+ });+ }escaping = false;continue;}@@ -10518,8 +10542,13 @@ mod tests {#[test]fn parses_command_text_with_quotes_and_escapes() {let argv = parse_command_argv(r#"SET "user:1" "Ada \"Lovelace\"""#).unwrap();-assert_eq!(argv, vec!["SET", "user:1", "Ada \"Lovelace\""]);++ let argv = parse_command_argv(r#"DEL "cache\\session""#).unwrap();+ assert_eq!(argv, vec!["DEL", "cache\\session"]);++ let argv = parse_command_argv(r#"DEL "bin\x00key\xff""#).unwrap();+ assert_eq!(argv, vec!["DEL", "bin\0key\u{ff}"]);}#[test]