feat(redis): edit hash fields

This commit is contained in:
onenewcode authored and GitHub committed 2026-08-26 14:44:19 +08:00
1 parent 75c2dc5e17
commit 0f9d32e1f5
18 files changed
+470 -14

No files matched your search

@@ -173,6 +173,10 @@ const selectedMemberContext = ref<RedisMemberContext | null>(null);
const isEditingMember = ref(false); const isEditingMember = ref(false);
const savingMember = ref(false); const savingMember = ref(false);
const memberEditValue = ref(""); 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 editingZsetMemberKey = ref<string | null>(null);
const savingZsetMember = ref(false); const savingZsetMember = ref(false);
const zsetInlineMember = ref(""); 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 redisJsonValueChanged = computed(() => data.value?.data.kind === "json" && editValue.value !== redisJsonDraftBaseline.value);
const canEditCurrentMemberFormat = computed(() => selectedMemberCanEdit.value && memberValueView.value === "utf8"); 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 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(() => { const memberValueChanged = computed(() => {
if (!selectedMemberCanEdit.value) return false; if (!selectedMemberCanEdit.value) return false;
const original = selectedMemberDetail.value.rawText; const original = selectedMemberDetail.value.rawText;
if (isEditingHashJson.value && selectedMemberDetail.value.json) return memberEditValue.value !== memberJsonDraftBaseline.value; const valueChanged = isEditingHashJson.value && selectedMemberDetail.value.json ? memberEditValue.value !== memberJsonDraftBaseline.value : memberEditValue.value !== original;
return memberEditValue.value !== original; return valueChanged || memberFieldChanged.value;
}); });
// A member sheet can close without discarding its draft, so its dirty state // A member sheet can close without discarding its draft, so its dirty state
// must outlive the sheet and whichever display format is currently selected. // must outlive the sheet and whichever display format is currently selected.
const memberDraftFormat = ref<"utf8" | "json" | null>(null); const memberDraftFormat = ref<"utf8" | "json" | null>(null);
const hasRetainedMemberDraft = computed(() => { const hasRetainedMemberDraft = computed(() => {
const format = memberDraftFormat.value; const format = memberDraftFormat.value;
if (memberFieldChanged.value) return true;
if (!format || !selectedMemberCanEdit.value) return false; if (!format || !selectedMemberCanEdit.value) return false;
const original = selectedMemberDetail.value.rawText; const original = selectedMemberDetail.value.rawText;
@@ -609,7 +618,7 @@ const hasRetainedMemberDraft = computed(() => {
} }
return memberEditValue.value !== original; 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 hasMore = computed(() => scanCursor.value != null && scanCursor.value > 0);
const collectionTotal = computed(() => (data.value ? redisValueCollectionTotal(data.value) : null)); const collectionTotal = computed(() => (data.value ? redisValueCollectionTotal(data.value) : null));
const hashFieldTtlSupported = computed(() => { const hashFieldTtlSupported = computed(() => {
@@ -1824,6 +1833,8 @@ function selectMember(title: string, value: unknown, context: RedisMemberContext
memberJsonRawBaseline.value = detail.json?.formattedText ?? ""; memberJsonRawBaseline.value = detail.json?.formattedText ?? "";
memberJsonDraftBaseline.value = jsonDraftBaseline(memberJsonRawBaseline.value, redisJsonDecoded.value); memberJsonDraftBaseline.value = jsonDraftBaseline(memberJsonRawBaseline.value, redisJsonDecoded.value);
memberEditValue.value = memberValueView.value === "json" && detail.json ? memberJsonDraftBaseline.value : detail.rawText; 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; memberDraftFormat.value = context.kind === "hash" && context.canEdit && memberValueView.value === "json" && detail.json ? "json" : null;
} }
@@ -1834,6 +1845,8 @@ function clearSelectedMember() {
selectedMemberContext.value = null; selectedMemberContext.value = null;
isEditingMember.value = false; isEditingMember.value = false;
memberEditValue.value = ""; memberEditValue.value = "";
memberFieldEditValue.value = "";
memberFieldDraftBaseline.value = "";
memberJsonDraftBaseline.value = ""; memberJsonDraftBaseline.value = "";
memberDraftFormat.value = null; memberDraftFormat.value = null;
} }
@@ -1857,7 +1870,9 @@ function viewMember(title: string, value: unknown, context: RedisMemberContext,
function handleMemberDetailOpenChange(open: boolean) { function handleMemberDetailOpenChange(open: boolean) {
showMemberDetail.value = open; showMemberDetail.value = open;
if (!open) isEditingMember.value = false; if (!open) {
isEditingMember.value = false;
}
} }
function finishMemberDetailClose() { function finishMemberDetailClose() {
@@ -1988,6 +2003,11 @@ function startEditMember() {
if (!memberValueChanged.value) memberEditValue.value = selectedMemberDetail.value.rawText; if (!memberValueChanged.value) memberEditValue.value = selectedMemberDetail.value.rawText;
// Do not demote a retained JSON draft to utf8; save still needs compact normalization. // Do not demote a retained JSON draft to utf8; save still needs compact normalization.
if (memberDraftFormat.value !== "json") memberDraftFormat.value = "utf8"; 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; isEditingMember.value = true;
nextTick(() => memberTextareaRef.value?.focus()); nextTick(() => memberTextareaRef.value?.focus());
} }
@@ -1996,6 +2016,7 @@ function cancelEditMember() {
memberEditValue.value = selectedMemberDetail.value.rawText; memberEditValue.value = selectedMemberDetail.value.rawText;
memberDraftFormat.value = null; memberDraftFormat.value = null;
isEditingMember.value = false; isEditingMember.value = false;
memberFieldEditValue.value = memberFieldDraftBaseline.value;
} }
function discardHashJsonEdit() { function discardHashJsonEdit() {
@@ -2020,13 +2041,24 @@ async function saveMemberEdit() {
} }
let nextContext: RedisMemberContext = context; 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; savingMember.value = true;
try { try {
if (context.kind === "list") { if (context.kind === "list") {
await api.redisListSet(props.connectionId, props.db, props.keyRaw, context.index, writeValue); await api.redisListSet(props.connectionId, props.db, props.keyRaw, context.index, writeValue);
} else if (context.kind === "hash") { } else if (context.kind === "hash") {
if (!context.field) return; if (context.field == null) return;
await api.redisHashSet(props.connectionId, props.db, props.keyRaw, context.field, writeValue); 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") { } else if (context.kind === "set") {
if (!context.member) return; if (!context.member) return;
await api.redisSetRemove(props.connectionId, props.db, props.keyRaw, context.member); await api.redisSetRemove(props.connectionId, props.db, props.keyRaw, context.member);
@@ -2149,7 +2181,7 @@ function resolveSelectedMember(context: RedisMemberContext): { title: string; va
}; };
} }
case "hash": { 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); const item = (collectionItems.value as RedisHashItem[]).find((candidate) => redisBlobText(candidate.field) === context.field);
if (!item) return null; if (!item) return null;
const field = redisBlobText(item.field); const field = redisBlobText(item.field);
@@ -3480,7 +3512,8 @@ defineExpose({ focusSearch });
/> />
<DialogHeader class="border-b px-5 py-4 pr-12"> <DialogHeader class="border-b px-5 py-4 pr-12">
<DialogTitle class="flex items-center gap-2"> <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 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')"> <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" /> <FileArchive class="h-3 w-3 mr-1" />
@@ -3596,7 +3629,7 @@ defineExpose({ focusSearch });
<Button variant="ghost" :disabled="savingMember" @click="cancelEditMember"> <Button variant="ghost" :disabled="savingMember" @click="cancelEditMember">
{{ t("grid.discard") }} {{ t("grid.discard") }}
</Button> </Button>
<Button :disabled="savingMember" @click="saveMemberEdit"> <Button :disabled="savingMember || !memberValueChanged" @click="saveMemberEdit">
<Loader2 v-if="savingMember" class="h-4 w-4 animate-spin" /> <Loader2 v-if="savingMember" class="h-4 w-4 animate-spin" />
<Save v-else class="h-4 w-4" /> <Save v-else class="h-4 w-4" />
{{ t("grid.save") }} {{ t("grid.save") }}
+1
View File
@@ -4727,6 +4727,7 @@ export default {
createFieldRequired: "Enter a hash field", createFieldRequired: "Enter a hash field",
createScoreInvalid: "Enter a valid score", createScoreInvalid: "Enter a valid score",
jsonModuleNotAvailable: "ReJSON module is not loaded on this Redis server", jsonModuleNotAvailable: "ReJSON module is not loaded on this Redis server",
field: "Field",
fieldRequired: "Enter a field name", fieldRequired: "Enter a field name",
valueRequired: "Enter a value", valueRequired: "Enter a value",
memberRequired: "Enter a member", memberRequired: "Enter a member",
+1
View File
@@ -4647,6 +4647,7 @@ export default withEnglishFallback({
keyspace: "Espacio de claves", keyspace: "Espacio de claves",
}, },
}, },
field: "campo",
}, },
mongo: { mongo: {
documents: "{count} documentos", documents: "{count} documentos",
+1
View File
@@ -4645,6 +4645,7 @@ export default withEnglishFallback({
keyspace: "Spazio delle chiavi", keyspace: "Spazio delle chiavi",
}, },
}, },
field: "campo",
}, },
mongo: { mongo: {
documents: "{count} documenti", documents: "{count} documenti",
+1
View File
@@ -4674,6 +4674,7 @@ export default withEnglishFallback({
keyspace: "キースペース", keyspace: "キースペース",
}, },
}, },
field: "フィールド",
}, },
mongo: { mongo: {
documents: "{count}ドキュメント", documents: "{count}ドキュメント",
+1
View File
@@ -4647,6 +4647,7 @@ export default withEnglishFallback({
keyspace: "Espaço de chaves", keyspace: "Espaço de chaves",
}, },
}, },
field: "campo",
}, },
mongo: { mongo: {
documents: "{count} documentos", documents: "{count} documentos",
+1
View File
@@ -4712,6 +4712,7 @@ export default withEnglishFallback({
createFieldRequired: "请输入 hash 字段", createFieldRequired: "请输入 hash 字段",
createScoreInvalid: "请输入有效分数", createScoreInvalid: "请输入有效分数",
jsonModuleNotAvailable: "该 Redis 服务器未加载 ReJSON 模块", jsonModuleNotAvailable: "该 Redis 服务器未加载 ReJSON 模块",
field: "字段",
fieldRequired: "请输入字段名", fieldRequired: "请输入字段名",
valueRequired: "请输入值", valueRequired: "请输入值",
memberRequired: "请输入成员", memberRequired: "请输入成员",
+1
View File
@@ -3867,6 +3867,7 @@ export default withEnglishFallback({
createFieldRequired: "請輸入 hash 欄位", createFieldRequired: "請輸入 hash 欄位",
createScoreInvalid: "請輸入有效分數", createScoreInvalid: "請輸入有效分數",
jsonModuleNotAvailable: "該 Redis 伺服器未載入 ReJSON 模組", jsonModuleNotAvailable: "該 Redis 伺服器未載入 ReJSON 模組",
field: "欄位",
fieldRequired: "請輸入欄位名稱", fieldRequired: "請輸入欄位名稱",
valueRequired: "請輸入值", valueRequired: "請輸入值",
memberRequired: "請輸入成員", memberRequired: "請輸入成員",
@@ -172,13 +172,13 @@ describe("native RedisJSON editor", () => {
expect(saveStringCalls).toContain("api.redisSetString"); expect(saveStringCalls).toContain("api.redisSetString");
expect(saveStringText).toMatch(/redisSetString\([\s\S]*\bvalue\b/); 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("savingHashJson");
expect(saveMemberText).toContain('memberDraftFormat.value === "json"'); expect(saveMemberText).toContain('memberDraftFormat.value === "json"');
expect(saveMemberCalls).toContain("normalizeRedisJsonDraft"); expect(saveMemberCalls).toContain("normalizeRedisJsonDraft");
expect(saveMemberText).toContain("writeValue = normalized.compactText"); expect(saveMemberText).toContain("writeValue = normalized.compactText");
expect(saveMemberCalls).toContain("api.redisHashSet"); expect(saveMemberCalls).toContain("api.redisHashFieldUpdate");
expect(saveMemberText).toMatch(/redisHashSet\([\s\S]*\bwriteValue\b/); expect(saveMemberText).toMatch(/redisHashFieldUpdate\([\s\S]*\bwriteValue\b/);
// Editor pretty baseline also uses the source-preserving formatter. // Editor pretty baseline also uses the source-preserving formatter.
expect(findFunction("formatJsonText").getText()).toContain("formatJsonSource"); expect(findFunction("formatJsonText").getText()).toContain("formatJsonSource");
@@ -208,12 +208,12 @@ describe("native RedisJSON editor", () => {
const saved = normalizeRedisJsonDraft(opened.json!.formattedText); const saved = normalizeRedisJsonDraft(opened.json!.formattedText);
expect(saved).toEqual({ ok: true, compactText: DUPLICATE_MEMBER_COMPACT }); 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 saveMemberEdit = findFunction("saveMemberEdit");
const text = saveMemberEdit.getText(); const text = saveMemberEdit.getText();
expect(text).toContain("if (savingHashJson)"); expect(text).toContain("if (savingHashJson)");
expect(text).toContain("writeValue = normalized.compactText"); 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", () => { 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 hashSearch = findFunction("onHashSearch");
const viewMember = findFunction("viewMember"); const viewMember = findFunction("viewMember");
const setMemberValueFormat = findFunction("setMemberValueFormat"); 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 unsavedDraft = findVariableInitializer("hasUnsavedRedisDraft");
const textFormat = findFunction("isTextRedisFormat"); const textFormat = findFunction("isTextRedisFormat");
const labels = templateElements(parsedViewer.descriptor.template!.ast as unknown as TemplateElement); 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(setMemberValueFormat.getText()).toContain('memberDraftFormat.value = "utf8"');
expect(unsavedDraft.getText()).toContain("hasRetainedStringDraft.value"); expect(unsavedDraft.getText()).toContain("hasRetainedStringDraft.value");
expect(unsavedDraft.getText()).toContain("hasRetainedMemberDraft.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(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(stringValueView) || activeStructuredStringDetail || isDecompressCodec(stringValueCodec)")).toBe(true);
expect(labels.some((element) => element.tag === "label" && directiveExpression(element, "if") === "isTextRedisFormat(memberValueView) || activeStructuredMemberDetail || isDecompressCodec(memberValueCodec)")).toBe(true); expect(labels.some((element) => element.tag === "label" && directiveExpression(element, "if") === "isTextRedisFormat(memberValueView) || activeStructuredMemberDetail || isDecompressCodec(memberValueCodec)")).toBe(true);
+1
View File
@@ -468,6 +468,7 @@ export const redisDeleteKey = forward("redisDeleteKey");
export const redisRenameKey = forward("redisRenameKey"); export const redisRenameKey = forward("redisRenameKey");
export const redisHashSet = forward("redisHashSet"); export const redisHashSet = forward("redisHashSet");
export const redisHashDel = forward("redisHashDel"); export const redisHashDel = forward("redisHashDel");
export const redisHashFieldUpdate = forward("redisHashFieldUpdate");
export const redisHashFieldSetTtl = forward("redisHashFieldSetTtl"); export const redisHashFieldSetTtl = forward("redisHashFieldSetTtl");
export const redisHashFieldSetExpireAt = forward("redisHashFieldSetExpireAt"); export const redisHashFieldSetExpireAt = forward("redisHashFieldSetExpireAt");
export const redisListPush = forward("redisListPush"); export const redisListPush = forward("redisListPush");
+11
View File
@@ -2703,6 +2703,17 @@ export async function redisHashDel(connectionId: string, db: number, keyRaw: str
return post("/api/redis/hash-del", { connectionId, db, keyRaw, field }); 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> { 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 }); return post("/api/redis/hash-field-set-ttl", { connectionId, db, keyRaw, field, ttl });
} }
+11
View File
@@ -2590,6 +2590,17 @@ export async function redisHashDel(connectionId: string, db: number, keyRaw: str
return invoke("redis_hash_del", { connectionId, db, keyRaw, field }); 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> { 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 }); return invoke("redis_hash_field_set_ttl", { connectionId, db, keyRaw, field, ttl });
} }
+288
View File
@@ -2956,6 +2956,194 @@ where
redis::cmd("HDEL").arg(key).arg(field).query_async::<()>(con).await.map_err(|e| e.to_string()) 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> pub async fn list_push<C>(con: &mut C, key: &[u8], value: &str, ttl: Option<i64>) -> Result<(), String>
where where
C: ConnectionLike + Send + Sync + Unpin, C: ConnectionLike + Send + Sync + Unpin,
@@ -5120,6 +5308,106 @@ mod tests {
assert_eq!(con.command_count("HEXPIRE"), 1); 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] #[tokio::test]
async fn hash_field_expiry_commands_accept_expected_results() { async fn hash_field_expiry_commands_accept_expected_results() {
let mut con = FakeRedisConnection::new(vec![ let mut con = FakeRedisConnection::new(vec![
+37
View File
@@ -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( pub async fn redis_hash_field_set_ttl_in_db_core(
state: &AppState, state: &AppState,
connection_id: &str, connection_id: &str,
+1
View File
@@ -588,6 +588,7 @@ async fn main() {
.route("/redis/rename-key", post(routes::redis::rename_key)) .route("/redis/rename-key", post(routes::redis::rename_key))
.route("/redis/hash-set", post(routes::redis::hash_set)) .route("/redis/hash-set", post(routes::redis::hash_set))
.route("/redis/hash-del", post(routes::redis::hash_del)) .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-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/hash-field-set-expire-at", post(routes::redis::hash_field_set_expire_at))
.route("/redis/list-push", post(routes::redis::list_push)) .route("/redis/list-push", post(routes::redis::list_push))
+30
View File
@@ -148,6 +148,17 @@ pub struct RedisHashRequest {
pub ttl: Option<i64>, 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)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct RedisHashFieldTtlRequest { pub struct RedisHashFieldTtlRequest {
@@ -541,6 +552,25 @@ pub async fn hash_del(
Ok(Json(())) 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( pub async fn hash_field_set_ttl(
State(state): State<Arc<WebState>>, State(state): State<Arc<WebState>>,
Json(req): Json<RedisHashFieldTtlRequest>, Json(req): Json<RedisHashFieldTtlRequest>,
+23
View File
@@ -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 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] #[tauri::command]
pub async fn redis_hash_field_set_ttl( pub async fn redis_hash_field_set_ttl(
state: State<'_, Arc<AppState>>, state: State<'_, Arc<AppState>>,
+1
View File
@@ -2062,6 +2062,7 @@ pub fn run() {
commands::redis_cmd::redis_rename_key, commands::redis_cmd::redis_rename_key,
commands::redis_cmd::redis_hash_set, commands::redis_cmd::redis_hash_set,
commands::redis_cmd::redis_hash_del, 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_ttl,
commands::redis_cmd::redis_hash_field_set_expire_at, commands::redis_cmd::redis_hash_field_set_expire_at,
commands::redis_cmd::redis_list_push, commands::redis_cmd::redis_list_push,