feat(redis): add command-line query result mode

Closes #10099
This commit is contained in:
t8y2 committed 2026-09-27 12:36:33 +00:00
1 parent add378d643
commit 9c23e3198b
19 files changed
+488 -41

No files matched your search

@@ -22,9 +22,9 @@ function roundTrip(tabs: QueryTab[]) {
describe("openTabsPersistence originalSql round-trip", () => {
it("preserves per-tab output view state across a round-trip", () => {
const [restored] = roundTrip([queryTab({ uiState: { activeOutputView: "chart", resultPaneOpen: false } })]);
const [restored] = roundTrip([queryTab({ uiState: { activeOutputView: "chart", redisResultViewMode: "console", resultPaneOpen: false } })]);
expect(restored.uiState).toEqual({ activeOutputView: "chart", resultPaneOpen: false });
expect(restored.uiState).toEqual({ activeOutputView: "chart", redisResultViewMode: "console", resultPaneOpen: false });
});
it("preserves namespaced special-page state across a round-trip", () => {
@@ -17,6 +17,19 @@ function backend(name: ResultCacheBackend["name"], overrides: Partial<ResultCach
}
describe("tab result cache statement execution metadata", () => {
it("retains Redis console output through cache restore", () => {
const result = {
columns: ["result"],
rows: [["PONG"]],
affected_rows: 0,
execution_time_ms: 1,
sourceStatement: "PING",
redis_console_output: "PONG",
};
expect(decodeTabResultSnapshot(encodeTabResultSnapshot({ result, cachedAt: 1 }))?.result).toMatchObject({ sourceStatement: "PING", redis_console_output: "PONG" });
});
it("retains timing details for active, array and historical results through cache restore", async () => {
const { buildTabResultSnapshot } = await import("@/lib/tabs/tabResultCache");
const timing = { query_timings_ms: { agent_total: 40, pool_acquire: 20, pool_release: 2 }, client_prepare_ms: 3, client_result_ms: 4, timing_page_count: 2 };
@@ -97,4 +97,10 @@ describe("tabUiState", () => {
page: { query: { Panel: { count: 3 } } },
});
});
it("persists only supported Redis result view modes", () => {
expect(sanitizeTabUiState({ redisResultViewMode: "console" })).toEqual({ redisResultViewMode: "console" });
expect(sanitizeTabUiState({ redisResultViewMode: "grid" })).toEqual({ redisResultViewMode: "grid" });
expect(sanitizeTabUiState({ redisResultViewMode: "invalid" })).toBeUndefined();
});
});
@@ -152,9 +152,11 @@ const TAB_OUTPUT_VIEWS = new Set<TabOutputView>(["result", "summary", "explain",
function restoredTabUiState(tab: SavedOpenTab): QueryTab["uiState"] {
const activeOutputView = tab.uiState?.activeOutputView;
const redisResultViewMode = tab.uiState?.redisResultViewMode;
const resultPaneOpen = tab.uiState?.resultPaneOpen;
const restored: NonNullable<QueryTab["uiState"]> = {};
if (activeOutputView && TAB_OUTPUT_VIEWS.has(activeOutputView)) restored.activeOutputView = activeOutputView;
if (redisResultViewMode === "grid" || redisResultViewMode === "console") restored.redisResultViewMode = redisResultViewMode;
if (typeof resultPaneOpen === "boolean") restored.resultPaneOpen = resultPaneOpen;
if (tab.uiState?.page) {
const sanitized = sanitizeTabUiState({ page: tab.uiState.page });
+65 -1
View File
@@ -1,7 +1,52 @@
import { describe, expect, it } from "vitest";
import { redisCommandResultToQueryResult } from "@/lib/redis/redisQueryResult";
import { redisCommandResultToQueryResult, redisQueryResultsToConsoleEntries } from "@/lib/redis/redisQueryResult";
import { formatRedisConsoleError, formatRedisConsoleValue } from "@/lib/redis/redisValuePresentation";
import type { QueryResult } from "@/types/database";
describe("formatRedisConsoleValue", () => {
it("formats scalar, nil, integer, double, boolean and bulk-string replies", () => {
expect(formatRedisConsoleValue(null)).toBe("(nil)");
expect(formatRedisConsoleValue(42)).toBe("(integer) 42");
expect(formatRedisConsoleValue(1.5)).toBe("(double) 1.5");
expect(formatRedisConsoleValue(true)).toBe("(true)");
expect(formatRedisConsoleValue("hello")).toBe("hello");
expect(formatRedisConsoleValue("")).toBe('""');
});
it("numbers ordinary and nested arrays without collapsing nested values into JSON", () => {
expect(formatRedisConsoleValue(["one", 2, null, ["nested", false]])).toBe(['1) "one"', "2) (integer) 2", "3) (nil)", '4) 1) "nested"', " 2) (false)"].join("\n"));
});
it("renders HGETALL, WITHSCORES and RESP3 map replies as readable pairs", () => {
expect(formatRedisConsoleValue(["name", "alice", "age", "30"], "HGETALL profile")).toBe(['1) "name" => "alice"', '2) "age" => "30"'].join("\n"));
expect(formatRedisConsoleValue(["alice", "1.5", "bob", "2"], "ZRANGE scores 0 -1 WITHSCORES")).toBe(['1) "alice" => "1.5"', '2) "bob" => "2"'].join("\n"));
expect(
formatRedisConsoleValue([
{ key: "name", value: "alice" },
{ key: "visits", value: 3 },
]),
).toBe(['1) "name" => "alice"', '2) "visits" => (integer) 3'].join("\n"));
});
it("keeps INFO text readable and prefixes errors once", () => {
expect(formatRedisConsoleValue("# Server\nredis_version:7.4.2")).toBe("# Server\nredis_version:7.4.2");
expect(formatRedisConsoleError("ERR wrong number of arguments")).toBe("(error) ERR wrong number of arguments");
expect(formatRedisConsoleError("(error) already formatted")).toBe("(error) already formatted");
});
});
describe("redisCommandResultToQueryResult", () => {
it("keeps the existing scalar grid shape as the default while retaining console output", () => {
const result = redisCommandResultToQueryResult(7, 4.6, "DBSIZE");
expect(result).toMatchObject({
columns: ["result"],
rows: [["7"]],
affected_rows: 0,
execution_time_ms: 5,
redis_console_output: "(integer) 7",
});
});
it("pairs member/score rows for ZREVRANGE ... WITHSCORES instead of one row per array element", () => {
const flat = ["carol", "300", "bob", "200", "alice", "100"];
const result = redisCommandResultToQueryResult(flat, 5, "ZREVRANGE issue7229_repro:zset 0 -1 WITHSCORES");
@@ -71,4 +116,23 @@ describe("redisCommandResultToQueryResult", () => {
["bob", "2"],
]);
});
it("builds ordered console entries for multiple commands and errors", () => {
const first = { ...redisCommandResultToQueryResult("PONG", 1, "PING"), sourceStatement: "PING" };
const second = { ...redisCommandResultToQueryResult(["a", "b"], 2, "LRANGE items 0 -1"), sourceStatement: "LRANGE items 0 -1" };
const failed: QueryResult = {
columns: ["Error"],
rows: [["ERR invalid command"]],
affected_rows: 0,
execution_time_ms: 0,
execution_error: true,
sourceStatement: "BROKEN",
};
expect(redisQueryResultsToConsoleEntries([first, second, failed])).toEqual([
{ command: "PING", output: "PONG", error: false },
{ command: "LRANGE items 0 -1", output: ['1) "a"', '2) "b"'].join("\n"), error: false },
{ command: "BROKEN", output: "(error) ERR invalid command", error: true },
]);
});
});
+27 -25
View File
@@ -1,29 +1,26 @@
import type { QueryResult } from "@/types/database";
import { formatRedisCommandResult } from "@/lib/redis/redisValuePresentation";
import { formatRedisCommandResult, formatRedisConsoleError, formatRedisConsoleValue, redisCommandResultPairKind } from "@/lib/redis/redisValuePresentation";
const KEY_VALUE_COMMANDS = new Set(["HGETALL"]);
// Sorted-set commands whose WITHSCORES modifier returns a flat member/score array.
const WITHSCORES_COMMANDS = new Set(["ZRANGE", "ZREVRANGE", "ZRANGEBYSCORE", "ZREVRANGEBYSCORE", "ZRANDMEMBER", "ZDIFF", "ZINTER", "ZUNION"]);
const WITHSCORES_MODIFIER = /\bWITHSCORES\b/i;
function commandHead(command: string): string {
return command.trim().split(/\s+/, 1)[0]?.toUpperCase() ?? "";
export interface RedisQueryConsoleEntry {
command: string;
output: string;
error: boolean;
}
function isKeyValueCommand(command: string): boolean {
return KEY_VALUE_COMMANDS.has(commandHead(command));
}
// ZRANGE/ZREVRANGE/ZRANGEBYSCORE/ZDIFF/ZINTER/ZUNION/... with a WITHSCORES modifier
// return a flat [member1, score1, member2, score2, ...] array — pair it up instead of
// dumping each element as its own row. Gate on the command head so a key or argument
// that merely contains the token WITHSCORES cannot trigger pairing.
function hasWithScoresModifier(command: string): boolean {
return WITHSCORES_COMMANDS.has(commandHead(command)) && WITHSCORES_MODIFIER.test(command);
export function redisQueryResultsToConsoleEntries(results: readonly QueryResult[]): RedisQueryConsoleEntry[] {
return results.flatMap((result) => {
const error = result.execution_error === true;
const output = error ? formatRedisConsoleError(result.rows[0]?.[0]) : result.redis_console_output;
if (output === undefined) return [];
return [{ command: result.sourceStatement?.trim() ?? "", output, error }];
});
}
export function redisCommandResultToQueryResult(value: unknown, elapsedMs: number, command?: string): QueryResult {
if (Array.isArray(value) && command && isKeyValueCommand(command)) {
const execution_time_ms = Math.max(0, Math.round(elapsedMs));
const redis_console_output = formatRedisConsoleValue(value, command);
const pairKind = redisCommandResultPairKind(command);
if (Array.isArray(value) && pairKind === "field-value") {
const rows: (string | number | boolean | null)[][] = [];
for (let i = 0; i + 1 < value.length; i += 2) {
rows.push([formatRedisCommandResult(value[i]), formatRedisCommandResult(value[i + 1])]);
@@ -32,10 +29,11 @@ export function redisCommandResultToQueryResult(value: unknown, elapsedMs: numbe
columns: ["field", "value"],
rows,
affected_rows: value.length / 2,
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
execution_time_ms,
redis_console_output,
};
}
if (Array.isArray(value) && command && hasWithScoresModifier(command)) {
if (Array.isArray(value) && pairKind === "member-score") {
const rows: (string | number | boolean | null)[][] = [];
for (let i = 0; i + 1 < value.length; i += 2) {
rows.push([formatRedisCommandResult(value[i]), formatRedisCommandResult(value[i + 1])]);
@@ -44,7 +42,8 @@ export function redisCommandResultToQueryResult(value: unknown, elapsedMs: numbe
columns: ["member", "score"],
rows,
affected_rows: rows.length,
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
execution_time_ms,
redis_console_output,
};
}
// INFO commands in cluster mode → [[node_addr, info_text], ...] pairs.
@@ -55,7 +54,8 @@ export function redisCommandResultToQueryResult(value: unknown, elapsedMs: numbe
columns: ["(index)", "value"],
rows,
affected_rows: value.length,
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
execution_time_ms,
redis_console_output,
};
}
if (Array.isArray(value)) {
@@ -64,13 +64,15 @@ export function redisCommandResultToQueryResult(value: unknown, elapsedMs: numbe
columns: ["(index)", "value"],
rows,
affected_rows: value.length,
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
execution_time_ms,
redis_console_output,
};
}
return {
columns: ["result"],
rows: [[formatRedisCommandResult(value)]],
affected_rows: 0,
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
execution_time_ms,
redis_console_output,
};
}
@@ -207,6 +207,24 @@ export function formatRedisCommandResult(value: unknown): string {
return JSON.stringify(value, null, 2);
}
export type RedisCommandResultPairKind = "field-value" | "member-score";
const REDIS_KEY_VALUE_COMMANDS = new Set(["HGETALL"]);
// Sorted-set commands whose WITHSCORES modifier returns member/score pairs.
const REDIS_WITHSCORES_COMMANDS = new Set(["ZRANGE", "ZREVRANGE", "ZRANGEBYSCORE", "ZREVRANGEBYSCORE", "ZRANDMEMBER", "ZDIFF", "ZINTER", "ZUNION"]);
const REDIS_WITHSCORES_MODIFIER = /\bWITHSCORES\b/i;
function redisCommandHead(command: string | undefined): string {
return command?.trim().split(/\s+/, 1)[0]?.toUpperCase() ?? "";
}
export function redisCommandResultPairKind(command: string | undefined): RedisCommandResultPairKind | undefined {
const head = redisCommandHead(command);
if (REDIS_KEY_VALUE_COMMANDS.has(head)) return "field-value";
if (REDIS_WITHSCORES_COMMANDS.has(head) && command && REDIS_WITHSCORES_MODIFIER.test(command)) return "member-score";
return undefined;
}
/** RedisJSON source text stays out of JavaScript's numeric representation. */
export function redisJsonValueText(value: { value: string }): string {
return value.value;
@@ -222,6 +240,84 @@ function isRedisClusterInfoValue(value: unknown): value is [string, string][] {
return Array.isArray(value) && value.length > 0 && (value as unknown[]).every((item) => Array.isArray(item) && item.length === 2 && typeof item[0] === "string" && typeof item[1] === "string" && item[1].startsWith("# "));
}
interface RedisMapEntry {
key: unknown;
value: unknown;
}
function isRedisMapEntry(value: unknown): value is RedisMapEntry {
return typeof value === "object" && value !== null && !Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "key") && Object.prototype.hasOwnProperty.call(value, "value");
}
function isRedisPair(value: unknown): value is [unknown, unknown] {
return Array.isArray(value) && value.length === 2;
}
function quoteRedisString(value: string): string {
return JSON.stringify(formatRedisStringValue(value)) ?? '""';
}
function formatRedisConsoleScalar(value: unknown, nested: boolean): string {
if (value == null) return "(nil)";
if (typeof value === "string") {
const text = formatRedisStringValue(value);
if (nested) return quoteRedisString(value);
return text.length > 0 ? text : '""';
}
if (typeof value === "number") return Number.isInteger(value) ? `(integer) ${value}` : `(double) ${value}`;
if (typeof value === "bigint") return `(integer) ${value}`;
if (typeof value === "boolean") return value ? "(true)" : "(false)";
return String(value);
}
function prefixRedisConsoleLines(prefix: string, lines: string[]): string[] {
if (lines.length === 0) return [prefix.trimEnd()];
const padding = " ".repeat(prefix.length);
return [`${prefix}${lines[0]}`, ...lines.slice(1).map((line) => `${padding}${line}`)];
}
function formatRedisConsoleInline(value: unknown): string {
if (typeof value === "string") return quoteRedisString(value);
if (value == null || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return formatRedisConsoleScalar(value, true);
try {
return JSON.stringify(value) ?? String(value);
} catch {
return String(value);
}
}
function redisConsolePairs(value: unknown[], command: string | undefined): Array<[unknown, unknown]> | undefined {
if (value.length > 0 && value.every(isRedisMapEntry)) return (value as RedisMapEntry[]).map((entry): [unknown, unknown] => [entry.key, entry.value]);
if (!redisCommandResultPairKind(command)) return undefined;
if (value.length > 0 && value.every(isRedisPair)) return (value as Array<[unknown, unknown]>).map((entry): [unknown, unknown] => [entry[0], entry[1]]);
if (value.length % 2 !== 0) return undefined;
const pairs: Array<[unknown, unknown]> = [];
for (let index = 0; index < value.length; index += 2) pairs.push([value[index], value[index + 1]]);
return pairs;
}
function formatRedisConsolePairs(pairs: Array<[unknown, unknown]>): string[] {
if (pairs.length === 0) return ["(empty array)"];
return pairs.flatMap(([key, value], index) => prefixRedisConsoleLines(`${index + 1}) ${formatRedisConsoleInline(key)} => `, formatRedisConsoleLines(value, undefined, true)));
}
function formatRedisConsoleLines(value: unknown, command: string | undefined, nested: boolean): string[] {
if (Array.isArray(value)) {
if (value.length === 0) return ["(empty array)"];
const pairs = redisConsolePairs(value, command);
if (pairs) return formatRedisConsolePairs(pairs);
return value.flatMap((entry, index) => prefixRedisConsoleLines(`${index + 1}) `, formatRedisConsoleLines(entry, undefined, true)));
}
if (typeof value === "object" && value !== null) {
try {
return (JSON.stringify(value, null, 2) ?? String(value)).split("\n");
} catch {
return [String(value)];
}
}
return [formatRedisConsoleScalar(value, nested)];
}
/**
* Format a Redis command result for the **command console terminal** (RedisKeyBrowser.vue).
* Unlike `formatRedisCommandResult` (used by the query result table UI), this function
@@ -230,14 +326,21 @@ function isRedisClusterInfoValue(value: unknown): value is [string, string][] {
*
* - Cluster INFO `[[addr, infoText], ...]` → `"{addr}\n{infoText}"` per node, joined by newlines.
* - Plain string → passthrough (handles single-node INFO text correctly).
* - Everything else → JSON.stringify (arrays, objects, etc.).
* - Arrays use redis-cli-style numbered items, including nested arrays.
* - RESP3 maps plus HGETALL/WITHSCORES responses use readable key/value pairs.
* - Integers, doubles, booleans and nil retain visible Redis-style type markers.
*/
export function formatRedisConsoleValue(value: unknown): string {
export function formatRedisConsoleValue(value: unknown, command?: string): string {
if (isRedisClusterInfoValue(value)) {
return value.map(([addr, info]) => `${addr}\n${info}`).join("\n");
}
if (typeof value === "string") return formatRedisStringValue(value);
return JSON.stringify(value, null, 2);
return formatRedisConsoleLines(value, command, false).join("\n");
}
export function formatRedisConsoleError(message: unknown): string {
const text = formatRedisStringValue(message).trim();
if (/^\(error\)(?:\s|$)/i.test(text)) return text;
return `(error) ${text || "Unknown Redis error"}`;
}
export function parseRedisJsonDetail(value: unknown): RedisJsonDetail | null {
@@ -67,6 +67,7 @@ interface ColumnarQueryResult {
rowCount: number;
mongo_documents?: unknown[];
mongo_copy_documents?: unknown[];
redis_console_output?: string;
affected_rows: number;
execution_time_ms: number;
server_execute_time_us?: number;
@@ -361,6 +362,7 @@ function stripSessionIds(result: QueryResult | undefined): QueryResult | undefin
rows: result.rows.map((row) => [...row]),
mongo_documents: result.mongo_documents ? clonePlain(result.mongo_documents) : undefined,
mongo_copy_documents: result.mongo_copy_documents ? clonePlain(result.mongo_copy_documents) : undefined,
redis_console_output: result.redis_console_output,
affected_rows: result.affected_rows,
execution_time_ms: result.execution_time_ms,
server_execute_time_us: result.server_execute_time_us,
@@ -424,6 +426,7 @@ function toColumnarResult(result: QueryResult | undefined): ColumnarQueryResult
rowCount,
mongo_documents: result.mongo_documents ? clonePlain(result.mongo_documents) : undefined,
mongo_copy_documents: result.mongo_copy_documents ? clonePlain(result.mongo_copy_documents) : undefined,
redis_console_output: result.redis_console_output,
affected_rows: result.affected_rows,
execution_time_ms: result.execution_time_ms,
server_execute_time_us: result.server_execute_time_us,
@@ -459,6 +462,7 @@ function fromColumnarResult(result: ColumnarQueryResult | undefined): QueryResul
rows,
mongo_documents: result.mongo_documents ? clonePlain(result.mongo_documents) : undefined,
mongo_copy_documents: result.mongo_copy_documents ? clonePlain(result.mongo_copy_documents) : undefined,
redis_console_output: result.redis_console_output,
affected_rows: result.affected_rows,
execution_time_ms: result.execution_time_ms,
server_execute_time_us: result.server_execute_time_us,
+1
View File
@@ -105,6 +105,7 @@ export function sanitizeTabUiState(value: unknown): TabUiState | undefined {
const state = value as TabUiState;
const normalized: TabUiState = {};
if (state.activeOutputView && ["result", "summary", "explain", "chart", "messages", "profile"].includes(state.activeOutputView)) normalized.activeOutputView = state.activeOutputView;
if (state.redisResultViewMode === "grid" || state.redisResultViewMode === "console") normalized.redisResultViewMode = state.redisResultViewMode;
if (typeof state.resultPaneOpen === "boolean") normalized.resultPaneOpen = state.resultPaneOpen;
const sanitizedPage = sanitizeTabPageUiState(state.page);
if (sanitizedPage) {