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。

feat(redis): edit hash fields

onenewcode0f9d32e1f595
diff --git a/apps/desktop/src/components/redis/RedisValueViewer.vue b/apps/desktop/src/components/redis/RedisValueViewer.vue
index 629860b86b..ea973be330 100644
--- a/apps/desktop/src/components/redis/RedisValueViewer.vue
+++ b/apps/desktop/src/components/redis/RedisValueViewer.vue
@@ -173,6 +173,10 @@ const selectedMemberContext = ref<RedisMemberContext | null>(null);
const isEditingMember = ref(false);
const savingMember = ref(false);
const memberEditValue = ref("");
+const memberFieldEditValue = ref("");
+// Keep the original hash field separate from the editable draft so a rename
+// remains visible (and protected from refresh) after the detail dialog closes.
+const memberFieldDraftBaseline = ref("");
const editingZsetMemberKey = ref<string | null>(null);
const savingZsetMember = ref(false);
const zsetInlineMember = ref("");
@@ -590,17 +594,22 @@ const hasRetainedStringDraft = computed(() => isStringDraftDirty(stringDraftForm
const redisJsonValueChanged = computed(() => data.value?.data.kind === "json" && editValue.value !== redisJsonDraftBaseline.value);
const canEditCurrentMemberFormat = computed(() => selectedMemberCanEdit.value && memberValueView.value === "utf8");
const isEditingHashJson = computed(() => selectedMemberContext.value?.kind === "hash" && selectedMemberCanEdit.value && memberValueView.value === "json" && Boolean(selectedMemberDetail.value.json));
+const memberFieldChanged = computed(() => {
+ const context = selectedMemberContext.value;
+ return context?.kind === "hash" && context.canEdit && memberFieldEditValue.value !== memberFieldDraftBaseline.value;
+});
const memberValueChanged = computed(() => {
if (!selectedMemberCanEdit.value) return false;
const original = selectedMemberDetail.value.rawText;
- if (isEditingHashJson.value && selectedMemberDetail.value.json) return memberEditValue.value !== memberJsonDraftBaseline.value;
- return memberEditValue.value !== original;
+ const valueChanged = isEditingHashJson.value && selectedMemberDetail.value.json ? memberEditValue.value !== memberJsonDraftBaseline.value : memberEditValue.value !== original;
+ return valueChanged || memberFieldChanged.value;
});
// A member sheet can close without discarding its draft, so its dirty state
// must outlive the sheet and whichever display format is currently selected.
const memberDraftFormat = ref<"utf8" | "json" | null>(null);
const hasRetainedMemberDraft = computed(() => {
const format = memberDraftFormat.value;
+ if (memberFieldChanged.value) return true;
if (!format || !selectedMemberCanEdit.value) return false;
const original = selectedMemberDetail.value.rawText;
@@ -609,7 +618,7 @@ const hasRetainedMemberDraft = computed(() => {
}
return memberEditValue.value !== original;
});
-const hasUnsavedRedisDraft = computed(() => hasRetainedStringDraft.value || redisJsonValueChanged.value || hasRetainedMemberDraft.value || editingZsetMemberKey.value !== null || showHashFieldTtlDialog.value);
+const hasUnsavedRedisDraft = computed(() => hasRetainedStringDraft.value || redisJsonValueChanged.value || hasRetainedMemberDraft.value || memberFieldChanged.value || editingZsetMemberKey.value !== null || showHashFieldTtlDialog.value);
const hasMore = computed(() => scanCursor.value != null && scanCursor.value > 0);
const collectionTotal = computed(() => (data.value ? redisValueCollectionTotal(data.value) : null));
const hashFieldTtlSupported = computed(() => {
@@ -1824,6 +1833,8 @@ function selectMember(title: string, value: unknown, context: RedisMemberContext
memberJsonRawBaseline.value = detail.json?.formattedText ?? "";
memberJsonDraftBaseline.value = jsonDraftBaseline(memberJsonRawBaseline.value, redisJsonDecoded.value);
memberEditValue.value = memberValueView.value === "json" && detail.json ? memberJsonDraftBaseline.value : detail.rawText;
+ memberFieldDraftBaseline.value = context.kind === "hash" ? (context.field ?? "") : "";
+ memberFieldEditValue.value = memberFieldDraftBaseline.value;
memberDraftFormat.value = context.kind === "hash" && context.canEdit && memberValueView.value === "json" && detail.json ? "json" : null;
}
@@ -1834,6 +1845,8 @@ function clearSelectedMember() {
selectedMemberContext.value = null;
isEditingMember.value = false;
memberEditValue.value = "";
+ memberFieldEditValue.value = "";
+ memberFieldDraftBaseline.value = "";
memberJsonDraftBaseline.value = "";
memberDraftFormat.value = null;
}
@@ -1857,7 +1870,9 @@ function viewMember(title: string, value: unknown, context: RedisMemberContext,
function handleMemberDetailOpenChange(open: boolean) {
showMemberDetail.value = open;
- if (!open) isEditingMember.value = false;
+ if (!open) {
+ isEditingMember.value = false;
+ }
}
function finishMemberDetailClose() {
@@ -1988,6 +2003,11 @@ function startEditMember() {
if (!memberValueChanged.value) memberEditValue.value = selectedMemberDetail.value.rawText;
// Do not demote a retained JSON draft to utf8; save still needs compact normalization.
if (memberDraftFormat.value !== "json") memberDraftFormat.value = "utf8";
+ // A closed dialog can be reopened into the same edit. Keep a dirty field
+ // draft instead of replacing it with the currently stored field name.
+ if (selectedMemberContext.value?.kind === "hash" && !memberFieldChanged.value) {
+ memberFieldEditValue.value = selectedMemberContext.value.field ?? "";
+ }
isEditingMember.value = true;
nextTick(() => memberTextareaRef.value?.focus());
}
@@ -1996,6 +2016,7 @@ function cancelEditMember() {
memberEditValue.value = selectedMemberDetail.value.rawText;
memberDraftFormat.value = null;
isEditingMember.value = false;
+ memberFieldEditValue.value = memberFieldDraftBaseline.value;
}
function discardHashJsonEdit() {
@@ -2020,13 +2041,24 @@ async function saveMemberEdit() {
}
let nextContext: RedisMemberContext = context;
+ const nextHashField = context.kind === "hash" ? memberFieldEditValue.value : "";
+ if (context.kind === "hash" && nextHashField.length === 0) {
+ toast(t("redis.fieldRequired"), 3000);
+ return;
+ }
savingMember.value = true;
try {
if (context.kind === "list") {
await api.redisListSet(props.connectionId, props.db, props.keyRaw, context.index, writeValue);
} else if (context.kind === "hash") {
- if (!context.field) return;
- await api.redisHashSet(props.connectionId, props.db, props.keyRaw, context.field, writeValue);
+ if (context.field == null) return;
+ try {
+ await api.redisHashFieldUpdate(props.connectionId, props.db, props.keyRaw, context.field, nextHashField, writeValue);
+ } catch (error) {
+ toast(errorMessage(error), 3000);
+ return;
+ }
+ nextContext = { kind: "hash", field: nextHashField, canEdit: canEditRedisMemberDetail("hash", writeValue) };
} else if (context.kind === "set") {
if (!context.member) return;
await api.redisSetRemove(props.connectionId, props.db, props.keyRaw, context.member);
@@ -2149,7 +2181,7 @@ function resolveSelectedMember(context: RedisMemberContext): { title: string; va
};
}
case "hash": {
- if (redisKind.value !== "hash" || !context.field) return null;
+ if (redisKind.value !== "hash" || context.field == null) return null;
const item = (collectionItems.value as RedisHashItem[]).find((candidate) => redisBlobText(candidate.field) === context.field);
if (!item) return null;
const field = redisBlobText(item.field);
@@ -3480,7 +3512,8 @@ defineExpose({ focusSearch });
/>
<DialogHeader class="border-b px-5 py-4 pr-12">
<DialogTitle class="flex items-center gap-2">
- <span class="truncate">{{ selectedMemberTitle ? formatValue(selectedMemberTitle) : t("redis.memberDetail") }}</span>
+ <Input v-if="isEditingMember && selectedMemberContext?.kind === 'hash'" v-model="memberFieldEditValue" class="h-7 min-w-0 flex-1 text-sm" :placeholder="t('redis.field')" :aria-label="t('redis.field')" @keydown.enter="saveMemberEdit" />
+ <span v-else class="truncate">{{ selectedMemberTitle ? formatValue(selectedMemberTitle) : t("redis.memberDetail") }}</span>
<Badge variant="outline" class="shrink-0 text-xs">{{ redisFormatLabel(memberValueView, selectedMemberDetail.rawLabel) }}</Badge>
<Badge v-if="memberGzipBadge && memberValueCodec === 'none'" variant="outline" class="shrink-0 text-xs text-muted-foreground" :title="t('redis.gzipBadgeTitle')" :aria-label="t('redis.gzipBadgeTitle')">
<FileArchive class="h-3 w-3 mr-1" />
@@ -3596,7 +3629,7 @@ defineExpose({ focusSearch });
<Button variant="ghost" :disabled="savingMember" @click="cancelEditMember">
{{ t("grid.discard") }}
</Button>
- <Button :disabled="savingMember" @click="saveMemberEdit">
+ <Button :disabled="savingMember || !memberValueChanged" @click="saveMemberEdit">
<Loader2 v-if="savingMember" class="h-4 w-4 animate-spin" />
<Save v-else class="h-4 w-4" />
{{ t("grid.save") }}
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index cd8db95ec0..00fafd6921 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -4727,6 +4727,7 @@ export default {
createFieldRequired: "Enter a hash field",
createScoreInvalid: "Enter a valid score",
jsonModuleNotAvailable: "ReJSON module is not loaded on this Redis server",
+ field: "Field",
fieldRequired: "Enter a field name",
valueRequired: "Enter a value",
memberRequired: "Enter a member",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 7011e0f000..b9ae2e9f70 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -4647,6 +4647,7 @@ export default withEnglishFallback({
keyspace: "Espacio de claves",
},
},
+ field: "campo",
},
mongo: {
documents: "{count} documentos",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index bf7953ad2a..9849a53b8c 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -4645,6 +4645,7 @@ export default withEnglishFallback({
keyspace: "Spazio delle chiavi",
},
},
+ field: "campo",
},
mongo: {
documents: "{count} documenti",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index eeb10788e7..5022a698f1 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -4674,6 +4674,7 @@ export default withEnglishFallback({
keyspace: "キースペース",
},
},
+ field: "フィールド",
},
mongo: {
documents: "{count}ドキュメント",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 9c0c6fb9f0..ceff64fff0 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -4647,6 +4647,7 @@ export default withEnglishFallback({
keyspace: "Espaço de chaves",
},
},
+ field: "campo",
},
mongo: {
documents: "{count} documentos",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 682e4ff055..b9746b9a8f 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -4712,6 +4712,7 @@ export default withEnglishFallback({
createFieldRequired: "请输入 hash 字段",
createScoreInvalid: "请输入有效分数",
jsonModuleNotAvailable: "该 Redis 服务器未加载 ReJSON 模块",
+ field: "字段",
fieldRequired: "请输入字段名",
valueRequired: "请输入值",
memberRequired: "请输入成员",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 4ea4bf5f21..12a6c815b3 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -3867,6 +3867,7 @@ export default withEnglishFallback({
createFieldRequired: "請輸入 hash 欄位",
createScoreInvalid: "請輸入有效分數",
jsonModuleNotAvailable: "該 Redis 伺服器未載入 ReJSON 模組",
+ field: "欄位",
fieldRequired: "請輸入欄位名稱",
valueRequired: "請輸入值",
memberRequired: "請輸入成員",
diff --git a/apps/desktop/src/lib/__tests__/redis/RedisValueViewer.redisJson.spec.ts b/apps/desktop/src/lib/__tests__/redis/RedisValueViewer.redisJson.spec.ts
index aabc1f3efe..2ab0194197 100644
--- a/apps/desktop/src/lib/__tests__/redis/RedisValueViewer.redisJson.spec.ts
+++ b/apps/desktop/src/lib/__tests__/redis/RedisValueViewer.redisJson.spec.ts
@@ -172,13 +172,13 @@ describe("native RedisJSON editor", () => {
expect(saveStringCalls).toContain("api.redisSetString");
expect(saveStringText).toMatch(/redisSetString\([\s\S]*\bvalue\b/);
- // Hash JSON draft (editor open or retained after leaving JSON tab) compact-writes via HSET.
+ // Hash JSON draft (editor open or retained after leaving JSON tab) compact-writes via the atomic field update.
expect(saveMemberText).toContain("savingHashJson");
expect(saveMemberText).toContain('memberDraftFormat.value === "json"');
expect(saveMemberCalls).toContain("normalizeRedisJsonDraft");
expect(saveMemberText).toContain("writeValue = normalized.compactText");
- expect(saveMemberCalls).toContain("api.redisHashSet");
- expect(saveMemberText).toMatch(/redisHashSet\([\s\S]*\bwriteValue\b/);
+ expect(saveMemberCalls).toContain("api.redisHashFieldUpdate");
+ expect(saveMemberText).toMatch(/redisHashFieldUpdate\([\s\S]*\bwriteValue\b/);
// Editor pretty baseline also uses the source-preserving formatter.
expect(findFunction("formatJsonText").getText()).toContain("formatJsonSource");
@@ -208,12 +208,12 @@ describe("native RedisJSON editor", () => {
const saved = normalizeRedisJsonDraft(opened.json!.formattedText);
expect(saved).toEqual({ ok: true, compactText: DUPLICATE_MEMBER_COMPACT });
- // Wiring: hash path only normalizes when savingHashJson, then HSETs writeValue.
+ // Wiring: hash path only normalizes when savingHashJson, then atomically updates the field with writeValue.
const saveMemberEdit = findFunction("saveMemberEdit");
const text = saveMemberEdit.getText();
expect(text).toContain("if (savingHashJson)");
expect(text).toContain("writeValue = normalized.compactText");
- expect(callsIn(saveMemberEdit).map(calledName)).toEqual(expect.arrayContaining(["normalizeRedisJsonDraft", "api.redisHashSet"]));
+ expect(callsIn(saveMemberEdit).map(calledName)).toEqual(expect.arrayContaining(["normalizeRedisJsonDraft", "api.redisHashFieldUpdate"]));
});
it("keeps the native editor and export paths on the RedisJSON value-text contract", () => {
@@ -241,6 +241,11 @@ describe("native RedisJSON editor", () => {
const hashSearch = findFunction("onHashSearch");
const viewMember = findFunction("viewMember");
const setMemberValueFormat = findFunction("setMemberValueFormat");
+ const selectMember = findFunction("selectMember");
+ const startEditMember = findFunction("startEditMember");
+ const saveMemberEdit = findFunction("saveMemberEdit");
+ const memberValueChanged = findVariableInitializer("memberValueChanged");
+ const memberFieldChanged = findVariableInitializer("memberFieldChanged");
const unsavedDraft = findVariableInitializer("hasUnsavedRedisDraft");
const textFormat = findFunction("isTextRedisFormat");
const labels = templateElements(parsedViewer.descriptor.template!.ast as unknown as TemplateElement);
@@ -256,6 +261,14 @@ describe("native RedisJSON editor", () => {
expect(setMemberValueFormat.getText()).toContain('memberDraftFormat.value = "utf8"');
expect(unsavedDraft.getText()).toContain("hasRetainedStringDraft.value");
expect(unsavedDraft.getText()).toContain("hasRetainedMemberDraft.value");
+ expect(unsavedDraft.getText()).toContain("memberFieldChanged.value");
+ expect(memberFieldChanged.getText()).toContain("memberFieldDraftBaseline.value");
+ expect(memberValueChanged.getText()).toContain("memberFieldChanged.value");
+ expect(selectMember.getText()).toContain("memberFieldDraftBaseline.value");
+ expect(startEditMember.getText()).toContain("!memberFieldChanged.value");
+ expect(saveMemberEdit.getText()).toContain("memberFieldEditValue.value");
+ expect(saveMemberEdit.getText()).not.toContain("memberFieldEditValue.value.trim()");
+ expect(viewerSource).toContain(':disabled="savingMember || !memberValueChanged"');
expect(textFormat.getText()).toContain('format === "json"');
expect(labels.some((element) => element.tag === "label" && directiveExpression(element, "if") === "isTextRedisFormat(stringValueView) || activeStructuredStringDetail || isDecompressCodec(stringValueCodec)")).toBe(true);
expect(labels.some((element) => element.tag === "label" && directiveExpression(element, "if") === "isTextRedisFormat(memberValueView) || activeStructuredMemberDetail || isDecompressCodec(memberValueCodec)")).toBe(true);
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 38f00c76dc..e2091db075 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -468,6 +468,7 @@ export const redisDeleteKey = forward("redisDeleteKey");
export const redisRenameKey = forward("redisRenameKey");
export const redisHashSet = forward("redisHashSet");
export const redisHashDel = forward("redisHashDel");
+export const redisHashFieldUpdate = forward("redisHashFieldUpdate");
export const redisHashFieldSetTtl = forward("redisHashFieldSetTtl");
export const redisHashFieldSetExpireAt = forward("redisHashFieldSetExpireAt");
export const redisListPush = forward("redisListPush");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index c34551fad0..7a289feab9 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -2703,6 +2703,17 @@ export async function redisHashDel(connectionId: string, db: number, keyRaw: str
return post("/api/redis/hash-del", { connectionId, db, keyRaw, field });
}
+export async function redisHashFieldUpdate(connectionId: string, db: number, keyRaw: string, oldField: string, newField: string, value: string): Promise<void> {
+ return post("/api/redis/hash-field-update", {
+ connectionId,
+ db,
+ keyRaw,
+ oldField,
+ newField,
+ value,
+ });
+}
+
export async function redisHashFieldSetTtl(connectionId: string, db: number, keyRaw: string, field: string, ttl: number): Promise<void> {
return post("/api/redis/hash-field-set-ttl", { connectionId, db, keyRaw, field, ttl });
}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 4a0e56c987..f8dc125ccf 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -2590,6 +2590,17 @@ export async function redisHashDel(connectionId: string, db: number, keyRaw: str
return invoke("redis_hash_del", { connectionId, db, keyRaw, field });
}
+export async function redisHashFieldUpdate(connectionId: string, db: number, keyRaw: string, oldField: string, newField: string, value: string): Promise<void> {
+ return invoke("redis_hash_field_update", {
+ connectionId,
+ db,
+ keyRaw,
+ oldField,
+ newField,
+ value,
+ });
+}
+
export async function redisHashFieldSetTtl(connectionId: string, db: number, keyRaw: string, field: string, ttl: number): Promise<void> {
return invoke("redis_hash_field_set_ttl", { connectionId, db, keyRaw, field, ttl });
}
diff --git a/crates/dbx-core/src/db/redis_driver.rs b/crates/dbx-core/src/db/redis_driver.rs
index 5bcf21df21..223263e3ba 100644
--- a/crates/dbx-core/src/db/redis_driver.rs
+++ b/crates/dbx-core/src/db/redis_driver.rs
@@ -2956,6 +2956,194 @@ where
redis::cmd("HDEL").arg(key).arg(field).query_async::<()>(con).await.map_err(|e| e.to_string())
}
+/// Atomically update a hash field, optionally moving it to a new name.
+///
+/// The operation is intentionally implemented as one Lua script rather than
+/// as an HSET/HDEL pair. That keeps destination collision checks and the
+/// source deletion in the same server-side critical section. Hash-field
+/// expiry commands were introduced after hashes themselves, so the script
+/// probes them with `pcall` and preserves expiry when the server supports
+/// HTTL/HEXPIRE while remaining usable on older Redis versions. Permission
+/// errors are surfaced instead of being mistaken for an unsupported command,
+/// since silently dropping a field TTL would be data loss.
+pub async fn hash_field_update<C>(
+ con: &mut C,
+ key: &[u8],
+ old_field: &str,
+ new_field: &str,
+ value: &str,
+) -> Result<(), String>
+where
+ C: ConnectionLike + Send + Sync + Unpin,
+{
+ const SCRIPT: &str = r#"
+ local key = KEYS[1]
+ local old_field = ARGV[1]
+ local new_field = ARGV[2]
+ local value = ARGV[3]
+
+ -- Keep enough source state to undo a destination write if a later
+ -- command fails. EVAL itself is atomic, but Redis does not roll back
+ -- writes made before a Lua runtime error.
+ if redis.call('HEXISTS', key, old_field) == 0 then
+ return 0
+ end
+ local old_value = redis.call('HGET', key, old_field)
+ if old_value == false then
+ return 0
+ end
+ if old_field ~= new_field and redis.call('HEXISTS', key, new_field) == 1 then
+ return -1
+ end
+
+ if old_field ~= new_field then
+ -- The collision check established that new_field is absent. Probe
+ -- HDEL before writing so a restricted HDEL permission cannot
+ -- leave both fields behind after the later source delete.
+ local delete_probe = redis.pcall('HDEL', key, new_field)
+ if type(delete_probe) == 'table' and delete_probe.err ~= nil then
+ return -3
+ end
+ end
+
+ local function optional_expiry_error(reply)
+ if type(reply) ~= 'table' or reply.err == nil then
+ return false
+ end
+ local detail = string.lower(reply.err)
+ return string.find(detail, 'unknown command', 1, true) ~= nil
+ or string.find(detail, 'syntax error', 1, true) ~= nil
+ or string.find(detail, 'unsupported', 1, true) ~= nil
+ end
+
+ -- HTTL returns an array containing -1 (persistent), -2 (missing), or
+ -- the remaining seconds. Unsupported commands are deliberately
+ -- ignored so Redis versions without hash-field expiry still work.
+ local source_ttl = -2
+ local ttl_reply = redis.pcall('HTTL', key, 'FIELDS', 1, old_field)
+ if type(ttl_reply) == 'table' and ttl_reply.err ~= nil then
+ if not optional_expiry_error(ttl_reply) then
+ return -3
+ end
+ elseif type(ttl_reply) == 'table' and ttl_reply[1] ~= nil then
+ source_ttl = tonumber(ttl_reply[1])
+ if source_ttl == nil or source_ttl < -2 then
+ return -3
+ end
+ -- The source can expire between the initial HGET and HTTL. Do
+ -- not create a new field when the probe already says it is gone.
+ if source_ttl == -2 then
+ return 0
+ end
+ -- HTTL rounds down to seconds. HEXPIRE 0 deletes a field, so an
+ -- imminent expiry must abort before HSET rather than losing data.
+ if source_ttl == 0 then
+ return -3
+ end
+ end
+
+ local function restore_source()
+ local restored = redis.pcall('HSET', key, old_field, old_value)
+ if type(restored) == 'table' and restored.err ~= nil then
+ return false
+ end
+ if source_ttl > 0 then
+ local expiry = redis.pcall('HEXPIRE', key, source_ttl, 'FIELDS', 1, old_field)
+ if type(expiry) == 'table' and expiry.err ~= nil and not optional_expiry_error(expiry) then
+ return false
+ end
+ end
+ return true
+ end
+
+ local function apply_source_expiry(field)
+ if source_ttl < 0 then
+ return true
+ end
+ local expiry = redis.pcall('HEXPIRE', key, source_ttl, 'FIELDS', 1, field)
+ if type(expiry) == 'table' and expiry.err ~= nil then
+ -- A missing command is expected on Redis versions before
+ -- hash-field expiry. Other errors must fail safely.
+ return optional_expiry_error(expiry)
+ end
+ return type(expiry) == 'table' and tonumber(expiry[1]) == 1
+ end
+
+ local written = redis.pcall('HSET', key, new_field, value)
+ if type(written) == 'table' and written.err ~= nil then
+ return -3
+ end
+
+ if not apply_source_expiry(new_field) then
+ if old_field == new_field then
+ restore_source()
+ else
+ redis.pcall('HDEL', key, new_field)
+ end
+ return -3
+ end
+
+ if old_field == new_field then
+ return 1
+ end
+
+ local deleted = redis.pcall('HDEL', key, old_field)
+ if type(deleted) == 'table' and deleted.err ~= nil then
+ redis.pcall('HDEL', key, new_field)
+ return -3
+ end
+ if tonumber(deleted) ~= 1 then
+ redis.pcall('HDEL', key, new_field)
+ return 0
+ end
+ return 2
+ "#;
+
+ let result = redis::cmd("EVAL")
+ .arg(SCRIPT)
+ .arg(1)
+ .arg(key)
+ .arg(old_field)
+ .arg(new_field)
+ .arg(value)
+ .query_async::<i64>(con)
+ .await;
+
+ let result = match result {
+ Ok(result) => result,
+ Err(error) if is_hash_field_update_acl_compatibility_error(&error) => {
+ return Err(
+ "Atomic Redis hash field updates require the Redis EVAL and hash command permissions. Ask an administrator to grant them."
+ .to_string(),
+ );
+ }
+ Err(error) => return Err(error.to_string()),
+ };
+
+ match result {
+ 1 | 2 => Ok(()),
+ 0 => Err("The Redis hash field no longer exists. Refresh and try again.".to_string()),
+ -1 => Err("A Redis hash field with the new name already exists.".to_string()),
+ -3 => Err("Redis hash field update failed before completion.".to_string()),
+ _ => Err("Unexpected result while updating Redis hash field.".to_string()),
+ }
+}
+
+fn is_hash_field_update_acl_compatibility_error(error: &redis::RedisError) -> bool {
+ if error.code() != Some("NOPERM") {
+ return false;
+ }
+
+ let detail = error.detail().unwrap_or_default().to_ascii_lowercase();
+ detail.contains("eval")
+ || detail.contains("hexists")
+ || detail.contains("hget")
+ || detail.contains("hset")
+ || detail.contains("hdel")
+ || detail.contains("httl")
+ || detail.contains("hexpire")
+}
+
pub async fn list_push<C>(con: &mut C, key: &[u8], value: &str, ttl: Option<i64>) -> Result<(), String>
where
C: ConnectionLike + Send + Sync + Unpin,
@@ -5120,6 +5308,106 @@ mod tests {
assert_eq!(con.command_count("HEXPIRE"), 1);
}
+ #[tokio::test]
+ async fn hash_field_update_uses_one_atomic_script_and_carries_field_ttl() {
+ let mut con = FakeRedisConnection::new(vec![RedisRawValue::Int(2)]);
+
+ super::hash_field_update(&mut con, b"hash-key", "session", "account", "Grace").await.unwrap();
+
+ assert_eq!(con.command_count("EVAL"), 1);
+ // HSET/HDEL/HTTL/HEXPIRE are script body text, not independent
+ // requests. This guards the atomic path and its TTL handling.
+ assert_eq!(con.command_count("HSET"), 0);
+ assert_eq!(con.command_count("HDEL"), 0);
+ assert!(con.commands[0].contains("redis.call('HEXISTS'"));
+ assert!(con.commands[0].contains("redis.pcall('HTTL'"));
+ assert!(con.commands[0].contains("redis.pcall('HEXPIRE'"));
+ assert!(con.commands[0].contains("redis.pcall('HDEL'"));
+ assert!(con.commands[0].contains("local delete_probe"));
+ assert!(con.commands[0].contains("if source_ttl == 0 then"));
+ }
+
+ #[tokio::test]
+ async fn hash_field_update_rejects_destination_collisions_without_follow_up_commands() {
+ let mut con = FakeRedisConnection::new(vec![RedisRawValue::Int(-1)]);
+
+ let error = super::hash_field_update(&mut con, b"hash-key", "session", "account", "Grace").await.unwrap_err();
+
+ assert!(error.contains("new name already exists"));
+ assert_eq!(con.command_count("EVAL"), 1);
+ assert_eq!(con.commands.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn hash_field_update_reports_a_missing_source_field() {
+ let mut con = FakeRedisConnection::new(vec![RedisRawValue::Int(0)]);
+
+ let error = super::hash_field_update(&mut con, b"hash-key", "session", "account", "Grace").await.unwrap_err();
+
+ assert!(error.contains("no longer exists"));
+ assert_eq!(con.command_count("EVAL"), 1);
+ }
+
+ #[tokio::test]
+ async fn hash_field_update_supports_value_only_edits_without_renaming() {
+ let mut con = FakeRedisConnection::new(vec![RedisRawValue::Int(1)]);
+
+ super::hash_field_update(&mut con, b"hash-key", "session", "session", "Grace").await.unwrap();
+
+ assert_eq!(con.command_count("EVAL"), 1);
+ assert!(con.commands[0].contains("if old_field == new_field then"));
+ }
+
+ #[tokio::test]
+ async fn hash_field_update_keeps_failures_inside_the_atomic_operation() {
+ let failure = redis::make_extension_error("ERR".to_string(), Some("script command failed".to_string()));
+ let mut con = FakeRedisConnection::with_results(vec![Err(failure)]);
+
+ let error = super::hash_field_update(&mut con, b"hash-key", "session", "account", "Grace").await.unwrap_err();
+
+ assert!(error.contains("script command failed"));
+ assert_eq!(con.command_count("EVAL"), 1);
+ assert_eq!(con.command_count("HSET"), 0);
+ assert_eq!(con.command_count("HDEL"), 0);
+ }
+
+ #[tokio::test]
+ async fn hash_field_update_reports_restricted_eval_access_without_fallback() {
+ let mut con = FakeRedisConnection::with_results(vec![Err(noperm("eval"))]);
+
+ let error = super::hash_field_update(&mut con, b"hash-key", "session", "account", "Grace").await.unwrap_err();
+
+ assert!(error.contains("EVAL and hash command permissions"));
+ assert_eq!(con.command_count("EVAL"), 1);
+ assert_eq!(con.commands.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn hash_field_update_does_not_restore_a_source_that_disappeared_before_hdel() {
+ let mut con = FakeRedisConnection::new(vec![RedisRawValue::Int(2)]);
+
+ super::hash_field_update(&mut con, b"hash-key", "session", "account", "Grace").await.unwrap();
+
+ let script = &con.commands[0];
+ let delete_branch = script.find("if tonumber(deleted) ~= 1 then").expect("HDEL result branch");
+ let branch = &script[delete_branch..];
+ assert!(branch.contains("redis.pcall('HDEL', key, new_field)"));
+ assert!(branch.contains("return 0"));
+ assert!(!branch.contains("restore_source()"));
+ }
+
+ #[tokio::test]
+ async fn concurrent_hash_field_updates_use_serialized_evals_and_reject_the_loser() {
+ let mut con = FakeRedisConnection::new(vec![RedisRawValue::Int(2), RedisRawValue::Int(0)]);
+
+ super::hash_field_update(&mut con, b"hash-key", "session", "account", "Grace").await.unwrap();
+ let error = super::hash_field_update(&mut con, b"hash-key", "session", "profile", "Grace").await.unwrap_err();
+
+ assert!(error.contains("no longer exists"));
+ assert_eq!(con.command_count("EVAL"), 2);
+ assert_eq!(con.commands.len(), 2);
+ }
+
#[tokio::test]
async fn hash_field_expiry_commands_accept_expected_results() {
let mut con = FakeRedisConnection::new(vec![
diff --git a/crates/dbx-core/src/redis_ops.rs b/crates/dbx-core/src/redis_ops.rs
index 287500af28..d7420aaf6f 100644
--- a/crates/dbx-core/src/redis_ops.rs
+++ b/crates/dbx-core/src/redis_ops.rs
@@ -473,6 +473,43 @@ pub async fn redis_hash_del_in_db_core(
}
}
+/// Atomically update a Redis hash field and optionally rename it.
+///
+/// The driver executes the source check, destination collision check, value
+/// write, and old-field deletion in one EVAL on the connection for the hash
+/// key. Keeping the dispatch here mirrors the other Redis operations so
+/// standalone and cluster connections follow the same path.
+pub async fn redis_hash_field_update_in_db_core(
+ state: &AppState,
+ connection_id: &str,
+ db: u32,
+ key_raw: &str,
+ old_field: &str,
+ new_field: &str,
+ value: &str,
+) -> Result<(), String> {
+ ensure_redis_pool(state, connection_id).await?;
+ let connections = state.connections.read().await;
+ match connections.get(connection_id).ok_or("Not found")? {
+ PoolKind::Redis(redis) => {
+ let key = redis_driver::redis_key_raw_to_bytes(key_raw)?;
+ match redis {
+ RedisConnection::Direct(con) => {
+ let mut con = con.lock().await;
+ redis_driver::select_db(&mut *con, db).await?;
+ redis_driver::hash_field_update(&mut *con, &key, old_field, new_field, value).await
+ }
+ RedisConnection::Cluster(cluster) => {
+ redis_driver::ensure_cluster_db(db)?;
+ let mut con = redis_driver::cluster_key_connection(cluster, &key).await?;
+ redis_driver::hash_field_update(&mut con, &key, old_field, new_field, value).await
+ }
+ }
+ }
+ _ => Err("Not a Redis connection".to_string()),
+ }
+}
+
pub async fn redis_hash_field_set_ttl_in_db_core(
state: &AppState,
connection_id: &str,
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index 0f6b95dba0..e989b637a0 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -588,6 +588,7 @@ async fn main() {
.route("/redis/rename-key", post(routes::redis::rename_key))
.route("/redis/hash-set", post(routes::redis::hash_set))
.route("/redis/hash-del", post(routes::redis::hash_del))
+ .route("/redis/hash-field-update", post(routes::redis::hash_field_update))
.route("/redis/hash-field-set-ttl", post(routes::redis::hash_field_set_ttl))
.route("/redis/hash-field-set-expire-at", post(routes::redis::hash_field_set_expire_at))
.route("/redis/list-push", post(routes::redis::list_push))
diff --git a/crates/dbx-web/src/routes/redis.rs b/crates/dbx-web/src/routes/redis.rs
index 18d2953d51..e4ae92eab8 100644
--- a/crates/dbx-web/src/routes/redis.rs
+++ b/crates/dbx-web/src/routes/redis.rs
@@ -148,6 +148,17 @@ pub struct RedisHashRequest {
pub ttl: Option<i64>,
}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RedisHashFieldUpdateRequest {
+ pub connection_id: String,
+ pub db: u32,
+ pub key_raw: String,
+ pub old_field: String,
+ pub new_field: String,
+ pub value: String,
+}
+
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RedisHashFieldTtlRequest {
@@ -541,6 +552,25 @@ pub async fn hash_del(
Ok(Json(()))
}
+pub async fn hash_field_update(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<RedisHashFieldUpdateRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Atomic hash field update").await?;
+ dbx_core::redis_ops::redis_hash_field_update_in_db_core(
+ &state.app,
+ &req.connection_id,
+ req.db,
+ &req.key_raw,
+ &req.old_field,
+ &req.new_field,
+ &req.value,
+ )
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+
pub async fn hash_field_set_ttl(
State(state): State<Arc<WebState>>,
Json(req): Json<RedisHashFieldTtlRequest>,
diff --git a/src-tauri/src/commands/redis_cmd.rs b/src-tauri/src/commands/redis_cmd.rs
index 96157ec07e..2fc1563c59 100644
--- a/src-tauri/src/commands/redis_cmd.rs
+++ b/src-tauri/src/commands/redis_cmd.rs
@@ -213,6 +213,29 @@ pub async fn redis_hash_del(
dbx_core::redis_ops::redis_hash_del_in_db_core(&state, &connection_id, db, &key_raw, &field).await
}
+#[tauri::command]
+pub async fn redis_hash_field_update(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ db: u32,
+ key_raw: String,
+ old_field: String,
+ new_field: String,
+ value: String,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Atomic hash field update").await?;
+ dbx_core::redis_ops::redis_hash_field_update_in_db_core(
+ &state,
+ &connection_id,
+ db,
+ &key_raw,
+ &old_field,
+ &new_field,
+ &value,
+ )
+ .await
+}
+
#[tauri::command]
pub async fn redis_hash_field_set_ttl(
state: State<'_, Arc<AppState>>,
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 88846c3981..f0dec6fff2 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2062,6 +2062,7 @@ pub fn run() {
commands::redis_cmd::redis_rename_key,
commands::redis_cmd::redis_hash_set,
commands::redis_cmd::redis_hash_del,
+ commands::redis_cmd::redis_hash_field_update,
commands::redis_cmd::redis_hash_field_set_ttl,
commands::redis_cmd::redis_hash_field_set_expire_at,
commands::redis_cmd::redis_list_push,