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): add Redis syntax checking for query editor

haipengno180a390a4c0c6
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index e57f9ebe5b..30c5fef5e3 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -37,6 +37,7 @@ import { selectionMatchOccurrences } from "@/lib/codemirrorSelectionMatches";
import { isSchemaAware, isSingleDatabase } from "@/lib/databaseFeatureSupport";
import * as api from "@/lib/api";
import { areSqlSemanticDiagnosticsEqual, buildSqlParserErrorDiagnostic, buildSqlSemanticDiagnostics, shouldRunSqlSemanticDiagnostics, type SqlSemanticDiagnostic } from "@/lib/sqlSemanticDiagnostics";
+import { buildRedisSyntaxDiagnostics, shouldRunRedisDiagnostics } from "@/lib/redisSyntaxDiagnostics";
import type { SqlCompletionColumn, SqlCompletionForeignKey, SqlCompletionItem, SqlCompletionObject } from "@/lib/sqlCompletion";
import type { DatabaseType, SqlReferenceAnalysis, SqlTableReference, SqlTextSpan } from "@/types/database";
@@ -730,10 +731,19 @@ async function refreshSemanticDiagnostics() {
setSemanticDiagnostics([]);
return;
}
- if (props.databaseType === "mongodb" || props.databaseType === "elasticsearch" || props.databaseType === "redis") {
+ if (props.databaseType === "mongodb" || props.databaseType === "elasticsearch") {
setSemanticDiagnostics([]);
return;
}
+ if (props.databaseType === "redis") {
+ // Redis has no SQL semantics; run command-name / arity / quote / danger checks instead.
+ if (!shouldRunRedisDiagnostics(sql, currentView.state.selection.main.head)) {
+ scheduleSemanticDiagnostics(900);
+ return;
+ }
+ setSemanticDiagnostics(buildRedisSyntaxDiagnostics(sql));
+ return;
+ }
if (!shouldRunSqlSemanticDiagnostics(sql, currentView.state.selection.main.head, { databaseType: props.databaseType })) {
scheduleSemanticDiagnostics(1200);
return;
diff --git a/apps/desktop/src/lib/redisCommandTable.ts b/apps/desktop/src/lib/redisCommandTable.ts
new file mode 100644
index 0000000000..0a9605d7ca
--- /dev/null
+++ b/apps/desktop/src/lib/redisCommandTable.ts
@@ -0,0 +1,385 @@
+/**
+ * Static Redis command metadata, distilled from the official Redis command table
+ * (redis-doc `commands.json` / the `COMMAND` output). Kept offline and lightweight:
+ * we only retain what the editor syntax diagnostics need — `arity` and `group` —
+ * plus a `safety` hint for danger/write-command highlighting.
+ *
+ * Arity semantics (matches the Redis `COMMAND` reply, command name INCLUDED in the count):
+ * arity > 0 → the command takes exactly `arity` tokens (e.g. GET key → arity 2).
+ * arity < 0 → the command takes AT LEAST `-arity` tokens (e.g. MSET k v [k v ...] → arity -3).
+ *
+ * `safety` is aligned with the token-level sets in `redisCommandSafety.ts` (used to gate
+ * execution). Here it is recorded per-command (including subcommands) so diagnostics can
+ * be more precise than the first-token classification.
+ *
+ * Subcommands are keyed as `"MAIN SUB"` in UPPER CASE (e.g. `"CONFIG GET"`, `"XGROUP CREATE"`).
+ */
+import type { RedisCommandSafety } from "@/lib/redisCommandSafety";
+
+export interface RedisCommandSpec {
+ /** Token count including the command name. Positive = exact, negative = minimum (-N). */
+ arity: number;
+ /** Redis command group: string/list/hash/.../server. */
+ group: string;
+ /** Danger level for diagnostic highlighting. */
+ safety: RedisCommandSafety;
+}
+
+type Spec = [arity: number, group: string, safety?: RedisCommandSafety];
+
+// Compact tuple form → expanded into the record below.
+const RAW_COMMANDS: Record<string, Spec> = {
+ // ---- String ----
+ APPEND: [3, "string", "confirm"],
+ DECR: [2, "string", "confirm"],
+ DECRBY: [3, "string", "confirm"],
+ GET: [2, "string"],
+ GETDEL: [2, "string", "confirm"],
+ GETEX: [-2, "string"],
+ GETRANGE: [4, "string"],
+ GETSET: [3, "string", "confirm"],
+ INCR: [2, "string", "confirm"],
+ INCRBY: [3, "string", "confirm"],
+ INCRBYFLOAT: [3, "string", "confirm"],
+ LCS: [-3, "string"],
+ MGET: [-2, "string"],
+ MSET: [-3, "string", "confirm"],
+ MSETNX: [-3, "string", "confirm"],
+ PSETEX: [4, "string", "confirm"],
+ SET: [-3, "string", "confirm"],
+ SETEX: [4, "string", "confirm"],
+ SETNX: [3, "string", "confirm"],
+ SETRANGE: [4, "string", "confirm"],
+ STRLEN: [2, "string"],
+
+ // ---- Generic key ----
+ COPY: [-3, "generic", "confirm"],
+ DEL: [-2, "generic", "confirm"],
+ DUMP: [2, "generic"],
+ EXISTS: [-2, "generic"],
+ EXPIRE: [-3, "generic", "confirm"],
+ EXPIREAT: [-3, "generic", "confirm"],
+ KEYS: [2, "generic", "blocked"],
+ MIGRATE: [-6, "generic", "blocked"],
+ MOVE: [3, "generic", "confirm"],
+ OBJECT_ENCODING: [3, "generic"],
+ OBJECT_FREQ: [3, "generic"],
+ OBJECT_IDLETIME: [3, "generic"],
+ OBJECT_REFCOUNT: [3, "generic"],
+ OBJECT_HELP: [2, "generic"],
+ PERSIST: [2, "generic", "confirm"],
+ PEXPIRE: [-3, "generic", "confirm"],
+ PEXPIREAT: [-3, "generic", "confirm"],
+ PTTL: [2, "generic"],
+ RANDOMKEY: [1, "generic"],
+ RENAME: [3, "generic", "confirm"],
+ RENAMENX: [3, "generic", "confirm"],
+ RESTORE: [-4, "generic", "confirm"],
+ SCAN: [-2, "generic"],
+ SORT: [-2, "generic", "confirm"],
+ SORT_RO: [-2, "generic"],
+ TOUCH: [-2, "generic"],
+ TTL: [2, "generic"],
+ TYPE: [2, "generic"],
+ UNLINK: [-2, "generic", "confirm"],
+ WAIT: [3, "generic"],
+ WAITAOF: [4, "generic"],
+
+ // ---- List ----
+ BLMOVE: [6, "list"],
+ BLMPOP: [-4, "list"],
+ BLPOP: [-3, "list"],
+ BRPOP: [-3, "list"],
+ BRPOPLPUSH: [4, "list"],
+ LINDEX: [3, "list"],
+ LINSERT: [5, "list", "confirm"],
+ LLEN: [2, "list"],
+ LMOVE: [5, "list", "confirm"],
+ LMPOP: [-4, "list", "confirm"],
+ LPOP: [-2, "list", "confirm"],
+ LPOS: [-2, "list"],
+ LPUSH: [-3, "list", "confirm"],
+ LPUSHX: [-3, "list", "confirm"],
+ LRANGE: [4, "list"],
+ LREM: [4, "list", "confirm"],
+ LSET: [4, "list", "confirm"],
+ LTRIM: [4, "list", "confirm"],
+ RPOP: [-2, "list", "confirm"],
+ RPOPLPUSH: [4, "list", "confirm"],
+ RPUSH: [-3, "list", "confirm"],
+ RPUSHX: [-3, "list", "confirm"],
+
+ // ---- Hash ----
+ HDEL: [-3, "hash", "confirm"],
+ HEXISTS: [3, "hash"],
+ HGET: [3, "hash"],
+ HGETALL: [2, "hash"],
+ HINCRBY: [4, "hash", "confirm"],
+ HINCRBYFLOAT: [4, "hash", "confirm"],
+ HKEYS: [2, "hash"],
+ HLEN: [2, "hash"],
+ HMGET: [-3, "hash"],
+ HMSET: [-4, "hash", "confirm"],
+ HRANDFIELD: [-2, "hash"],
+ HSCAN: [-3, "hash"],
+ HSET: [-4, "hash", "confirm"],
+ HSETNX: [4, "hash", "confirm"],
+ HSTRLEN: [3, "hash"],
+ HVALS: [2, "hash"],
+
+ // ---- Set ----
+ SADD: [-3, "set", "confirm"],
+ SCARD: [2, "set"],
+ SDIFF: [-2, "set"],
+ SDIFFSTORE: [-3, "set", "confirm"],
+ SINTER: [-2, "set"],
+ SINTERCARD: [-3, "set"],
+ SINTERSTORE: [-3, "set", "confirm"],
+ SISMEMBER: [3, "set"],
+ SMEMBERS: [2, "set"],
+ SMISMEMBER: [-3, "set"],
+ SMOVE: [4, "set", "confirm"],
+ SPOP: [-2, "set", "confirm"],
+ SRANDMEMBER: [-2, "set"],
+ SREM: [-3, "set", "confirm"],
+ SSCAN: [-3, "set"],
+ SUNION: [-2, "set"],
+ SUNIONSTORE: [-3, "set", "confirm"],
+
+ // ---- Sorted set ----
+ BZMPOP: [-3, "zset"],
+ BZPOPMAX: [-3, "zset"],
+ BZPOPMIN: [-3, "zset"],
+ ZADD: [-4, "zset", "confirm"],
+ ZCARD: [2, "zset"],
+ ZCOUNT: [4, "zset"],
+ ZDIFF: [-3, "zset"],
+ ZDIFFSTORE: [-4, "zset", "confirm"],
+ ZINCRBY: [4, "zset", "confirm"],
+ ZINTER: [-3, "zset"],
+ ZINTERCARD: [-3, "zset"],
+ ZINTERSTORE: [-4, "zset", "confirm"],
+ ZLEXCOUNT: [4, "zset"],
+ ZMPOP: [-3, "zset", "confirm"],
+ ZMSCORE: [-3, "zset"],
+ ZPOPMAX: [-2, "zset", "confirm"],
+ ZPOPMIN: [-2, "zset", "confirm"],
+ ZRANGE: [-4, "zset"],
+ ZRANGEBYLEX: [-4, "zset"],
+ ZRANGEBYSCORE: [-4, "zset"],
+ ZRANGESTORE: [-5, "zset", "confirm"],
+ ZRANK: [-3, "zset"],
+ ZREM: [-3, "zset", "confirm"],
+ ZREMRANGEBYLEX: [4, "zset", "confirm"],
+ ZREMRANGEBYRANK: [4, "zset", "confirm"],
+ ZREMRANGEBYSCORE: [4, "zset", "confirm"],
+ ZREVRANGE: [-4, "zset"],
+ ZREVRANGEBYLEX: [-4, "zset"],
+ ZREVRANGEBYSCORE: [-4, "zset"],
+ ZREVRANK: [-3, "zset"],
+ ZSCAN: [-3, "zset"],
+ ZSCORE: [3, "zset"],
+ ZUNION: [-3, "zset"],
+ ZUNIONSTORE: [-4, "zset", "confirm"],
+
+ // ---- Bitmap ----
+ BITCOUNT: [-2, "bitmap"],
+ BITFIELD: [-2, "bitmap", "confirm"],
+ BITFIELD_RO: [-2, "bitmap"],
+ BITOP: [-4, "bitmap", "confirm"],
+ BITPOS: [-3, "bitmap"],
+ GETBIT: [3, "bitmap"],
+ SETBIT: [4, "bitmap", "confirm"],
+
+ // ---- Hyperloglog ----
+ PFADD: [-2, "hyperloglog", "confirm"],
+ PFCOUNT: [-2, "hyperloglog"],
+ PFMERGE: [-2, "hyperloglog", "confirm"],
+
+ // ---- Geo ----
+ GEOADD: [-5, "geo", "confirm"],
+ GEODIST: [-4, "geo"],
+ GEOHASH: [-3, "geo"],
+ GEOPOS: [-3, "geo"],
+ GEORADIUS: [-6, "geo", "confirm"],
+ GEORADIUS_RO: [-6, "geo"],
+ GEORADIUSBYMEMBER: [-5, "geo", "confirm"],
+ GEORADIUSBYMEMBER_RO: [-5, "geo"],
+ GEOSEARCH: [-7, "geo"],
+ GEOSEARCHSTORE: [-8, "geo", "confirm"],
+
+ // ---- Stream ----
+ XACK: [-4, "stream", "confirm"],
+ XADD: [-5, "stream", "confirm"],
+ XAUTOCLAIM: [-7, "stream", "confirm"],
+ XCLAIM: [-6, "stream", "confirm"],
+ XDEL: [-3, "stream", "confirm"],
+ "XGROUP CREATE": [-6, "stream", "confirm"],
+ "XGROUP CREATECONSUMER": [5, "stream", "confirm"],
+ "XGROUP DELCONSUMER": [4, "stream", "confirm"],
+ "XGROUP DESTROY": [4, "stream", "confirm"],
+ "XGROUP HELP": [2, "stream"],
+ "XGROUP SETID": [-5, "stream", "confirm"],
+ "XINFO CONSUMERS": [4, "stream"],
+ "XINFO GROUPS": [3, "stream"],
+ "XINFO HELP": [2, "stream"],
+ "XINFO STREAM": [-3, "stream"],
+ XLEN: [2, "stream"],
+ XPENDING: [-3, "stream"],
+ XRANGE: [-4, "stream"],
+ XREAD: [-4, "stream"],
+ XREADGROUP: [-7, "stream"],
+ XREVRANGE: [-4, "stream"],
+ XSETID: [-3, "stream", "confirm"],
+ XTRIM: [-4, "stream", "confirm"],
+
+ // ---- Pub/Sub ----
+ PSUBSCRIBE: [-2, "pubsub"],
+ PUBLISH: [3, "pubsub"],
+ "PUBSUB CHANNELS": [-2, "pubsub"],
+ "PUBSUB NUMPAT": [1, "pubsub"],
+ "PUBSUB NUMSUB": [-2, "pubsub"],
+ "PUBSUB SHARDCHANNELS": [-2, "pubsub"],
+ "PUBSUB SHARDNUMSUB": [-2, "pubsub"],
+ PUNSUBSCRIBE: [-1, "pubsub"],
+ SPUBLISH: [3, "pubsub"],
+ SSUBSCRIBE: [2, "pubsub"],
+ SUBSCRIBE: [-2, "pubsub"],
+ SUNSUBSCRIBE: [-1, "pubsub"],
+ UNSUBSCRIBE: [-1, "pubsub"],
+
+ // ---- Transactions ----
+ DISCARD: [1, "transactions"],
+ EXEC: [1, "transactions"],
+ MULTI: [1, "transactions"],
+ UNWATCH: [1, "transactions"],
+ WATCH: [-2, "transactions"],
+
+ // ---- Scripting ----
+ EVAL: [-3, "scripting", "blocked"],
+ EVALSHA: [-3, "scripting", "blocked"],
+ EVAL_RO: [-3, "scripting", "blocked"],
+ EVALSHA_RO: [-3, "scripting", "blocked"],
+ FCALL: [-3, "scripting"],
+ FCALL_RO: [-3, "scripting"],
+ "FUNCTION DELETE": [3, "scripting", "confirm"],
+ "FUNCTION DUMP": [2, "scripting"],
+ "FUNCTION FLUSH": [-2, "scripting", "confirm"],
+ "FUNCTION LIST": [-2, "scripting"],
+ "FUNCTION LOAD": [-3, "scripting", "confirm"],
+ "FUNCTION RESTORE": [-4, "scripting", "confirm"],
+ "FUNCTION STATS": [1, "scripting"],
+ "SCRIPT EXISTS": [-2, "scripting", "blocked"],
+ "SCRIPT FLUSH": [-2, "scripting", "blocked"],
+ "SCRIPT KILL": [1, "scripting", "blocked"],
+ "SCRIPT LOAD": [2, "scripting", "blocked"],
+
+ // ---- Connection ----
+ AUTH: [-2, "connection"],
+ ECHO: [2, "connection"],
+ HELLO: [-1, "connection"],
+ PING: [-1, "connection"],
+ QUIT: [1, "connection"],
+ RESET: [1, "connection"],
+ SELECT: [2, "connection"],
+ "CLIENT CACHING": [3, "connection"],
+ "CLIENT GETNAME": [1, "connection"],
+ "CLIENT GETREDIR": [1, "connection"],
+ "CLIENT ID": [1, "connection"],
+ "CLIENT INFO": [1, "connection"],
+ "CLIENT KILL": [-3, "connection", "confirm"],
+ "CLIENT LIST": [-2, "connection"],
+ "CLIENT NO-EVICT": [2, "connection"],
+ "CLIENT NO-TOUCH": [2, "connection"],
+ "CLIENT PAUSE": [-2, "connection"],
+ "CLIENT REPLY": [2, "connection"],
+ "CLIENT SETINFO": [-3, "connection"],
+ "CLIENT SETNAME": [3, "connection"],
+ "CLIENT TRACKING": [-3, "connection"],
+ "CLIENT TRACKINGINFO": [1, "connection"],
+ "CLIENT UNPAUSE": [1, "connection"],
+
+ // ---- Server ----
+ BGREWRITEAOF: [1, "server"],
+ BGSAVE: [-1, "server", "blocked"],
+ "COMMAND COUNT": [1, "server"],
+ "COMMAND DOCS": [-2, "server"],
+ "COMMAND GETKEYS": [-3, "server"],
+ "COMMAND INFO": [-2, "server"],
+ "COMMAND LIST": [-2, "server"],
+ "CONFIG GET": [-2, "server", "blocked"],
+ "CONFIG RESETSTAT": [1, "server", "blocked"],
+ "CONFIG REWRITE": [1, "server", "blocked"],
+ "CONFIG SET": [-3, "server", "blocked"],
+ DBSIZE: [1, "server"],
+ FAILOVER: [-1, "server", "confirm"],
+ FLUSHALL: [-1, "server", "blocked"],
+ FLUSHDB: [-1, "server", "confirm"],
+ INFO: [-1, "server"],
+ LASTSAVE: [1, "server"],
+ "MEMORY USAGE": [-3, "server"],
+ "MEMORY STATS": [1, "server"],
+ "MEMORY PURGE": [1, "server"],
+ "MEMORY DOCS": [1, "server"],
+ "MODULE LIST": [1, "server", "blocked"],
+ "MODULE LOAD": [-3, "server", "blocked"],
+ "MODULE LOADEX": [-3, "server", "blocked"],
+ "MODULE UNLOAD": [3, "server", "blocked"],
+ MONITOR: [1, "server"],
+ REPLICAOF: [3, "server", "blocked"],
+ ROLE: [1, "server"],
+ SAVE: [1, "server", "blocked"],
+ SHUTDOWN: [-1, "server", "blocked"],
+ SLAVEOF: [3, "server", "blocked"],
+ "SLOWLOG GET": [-2, "server"],
+ "SLOWLOG LEN": [1, "server"],
+ "SLOWLOG RESET": [1, "server"],
+ "SLOWLOG HELP": [1, "server"],
+ SWAPDB: [3, "server", "confirm"],
+ SYNC: [1, "server"],
+ TIME: [1, "server"],
+
+ // ---- Cluster ----
+ "CLUSTER ADDSLOTS": [-3, "cluster", "confirm"],
+ "CLUSTER COUNT-FAILURE-REPORTS": [2, "cluster"],
+ "CLUSTER COUNTKEYSINSLOT": [3, "cluster"],
+ "CLUSTER DELSLOTS": [-3, "cluster", "confirm"],
+ "CLUSTER FAILOVER": [-2, "cluster", "confirm"],
+ "CLUSTER FLUSHSLOTS": [1, "cluster", "confirm"],
+ "CLUSTER FORGET": [2, "cluster", "confirm"],
+ "CLUSTER GETKEYSINSLOT": [4, "cluster"],
+ "CLUSTER INFO": [1, "cluster"],
+ "CLUSTER KEYSLOT": [2, "cluster"],
+ "CLUSTER LINKS": [1, "cluster"],
+ "CLUSTER MEET": [-4, "cluster", "confirm"],
+ "CLUSTER MYID": [1, "cluster"],
+ "CLUSTER NODES": [1, "cluster"],
+ "CLUSTER REPLICAS": [2, "cluster"],
+ "CLUSTER REPLICATE": [2, "cluster", "confirm"],
+ "CLUSTER RESET": [-2, "cluster", "confirm"],
+ "CLUSTER SAVECONFIG": [1, "cluster", "confirm"],
+ "CLUSTER SET-CONFIG-EPOCH": [2, "cluster", "confirm"],
+ "CLUSTER SETSLOT": [-4, "cluster", "confirm"],
+ "CLUSTER SHARDS": [1, "cluster"],
+ "CLUSTER SLAVES": [2, "cluster"],
+ "CLUSTER SLOTS": [1, "cluster"],
+ READONLY: [1, "cluster"],
+ READWRITE: [1, "cluster"],
+};
+
+export const REDIS_COMMAND_TABLE: Record<string, RedisCommandSpec> = Object.fromEntries(Object.entries(RAW_COMMANDS).map(([name, [arity, group, safety]]) => [name.toUpperCase(), { arity, group, safety: safety ?? "allowed" }]));
+
+/**
+ * Resolve a command spec. Handles two-token subcommands (e.g. `XGROUP CREATE`,
+ * `CONFIG GET`) by trying `MAIN SUB` first, then falling back to the main token.
+ */
+export function resolveRedisCommandSpec(argvUpper: readonly string[]): RedisCommandSpec | undefined {
+ if (argvUpper.length === 0) return undefined;
+ const main = argvUpper[0];
+ if (argvUpper.length >= 2) {
+ const sub = `${main} ${argvUpper[1]}`;
+ const subSpec = REDIS_COMMAND_TABLE[sub];
+ if (subSpec) return subSpec;
+ }
+ return REDIS_COMMAND_TABLE[main];
+}
diff --git a/apps/desktop/src/lib/redisSyntaxDiagnostics.ts b/apps/desktop/src/lib/redisSyntaxDiagnostics.ts
new file mode 100644
index 0000000000..a29b4a3ef4
--- /dev/null
+++ b/apps/desktop/src/lib/redisSyntaxDiagnostics.ts
@@ -0,0 +1,224 @@
+/**
+ * Redis command syntax diagnostics for the query editor.
+ *
+ * Mirrors the shape of `sqlSemanticDiagnostics.ts` so the editor's diagnostic
+ * pipeline (StateField + Decoration.mark) can render them with no extra wiring.
+ * Diagnostics are produced per-line (one Redis command per line — matching the
+ * execution contract in `queryStore.executeTabSql`).
+ */
+import type { SqlTextSpan } from "@/types/database";
+import type { SqlSemanticDiagnostic } from "@/lib/sqlSemanticDiagnostics";
+import { resolveRedisCommandSpec } from "@/lib/redisCommandTable";
+
+export interface RedisArgvToken {
+ /** Token text (raw, case preserved). */
+ value: string;
+ /** 1-based start/end character columns within the source line. */
+ startColumn: number;
+ endColumn: number;
+}
+
+export interface RedisArgvResult {
+ argv: RedisArgvToken[];
+ /** True when a quoted string was not closed before end-of-line. */
+ unclosedQuote: boolean;
+ /** Column where an unclosed quote started (1-based), if any. */
+ unclosedQuoteStart?: number;
+}
+
+/**
+ * Tokenize a single Redis command line into argv, mirroring the server-side
+ * `parse_command_argv` rules (whitespace separation, single/double quotes,
+ * backslash escapes). Trailing `;` is stripped. Each token records its column
+ * span so diagnostics can underline the offending token.
+ */
+export function tokenizeRedisLine(line: string): RedisArgvResult {
+ const argv: RedisArgvToken[] = [];
+ let i = 0;
+ const n = line.length;
+ let unclosedQuote = false;
+ let unclosedQuoteStart: number | undefined;
+
+ while (i < n) {
+ // Skip whitespace.
+ while (i < n && (line[i] === " " || line[i] === "\t")) i++;
+ if (i >= n) break;
+
+ const startColumn = i + 1; // 1-based
+ let value = "";
+ let closed = false;
+ const ch = line[i];
+
+ if (ch === '"' || ch === "'") {
+ if (unclosedQuoteStart === undefined) unclosedQuoteStart = startColumn;
+ const quote = ch;
+ i++; // consume opening quote
+ let escaping = false;
+ while (i < n) {
+ const c = line[i];
+ if (escaping) {
+ value += c;
+ escaping = false;
+ i++;
+ continue;
+ }
+ if (c === "\\") {
+ escaping = true;
+ i++;
+ continue;
+ }
+ if (c === quote) {
+ i++; // consume closing quote
+ closed = true;
+ break;
+ }
+ value += c;
+ i++;
+ }
+ if (!closed && i >= n) {
+ unclosedQuote = true;
+ } else {
+ // If the quote was closed, allow trailing chars until whitespace as part
+ // of the same token (e.g. `"a"b` → `ab`) to match common tokenizers.
+ while (i < n && line[i] !== " " && line[i] !== "\t") {
+ value += line[i];
+ i++;
+ }
+ }
+ } else {
+ closed = true; // unquoted tokens are always complete
+ while (i < n && line[i] !== " " && line[i] !== "\t") {
+ if (line[i] === "\\") {
+ i++;
+ if (i < n) {
+ value += line[i];
+ i++;
+ }
+ continue;
+ }
+ value += line[i];
+ i++;
+ }
+ }
+
+ // Strip a single trailing semicolon (line-level `;` terminator).
+ if (value.endsWith(";")) value = value.slice(0, -1);
+
+ if (value.length > 0 || !closed) {
+ argv.push({ value, startColumn, endColumn: i + 1 });
+ }
+ }
+
+ return { argv, unclosedQuote, unclosedQuoteStart };
+}
+
+function aritySatisfied(arity: number, tokenCount: number): boolean {
+ if (arity > 0) return tokenCount === arity;
+ if (arity < 0) return tokenCount >= -arity;
+ return true; // arity 0 — unspecified, accept anything
+}
+
+function describeArity(arity: number): string {
+ if (arity > 0) return `exactly ${arity - 1} argument${arity - 1 === 1 ? "" : "s"}`;
+ if (arity < 0) return `at least ${-arity - 1} argument${-arity - 1 === 1 ? "" : "s"}`;
+ return "any number of arguments";
+}
+
+function lineSpan(lineIndex: number, startColumn: number, endColumn: number): SqlTextSpan {
+ // SqlTextSpan columns are 1-based and inclusive; map onto the physical line.
+ return {
+ start_line: lineIndex,
+ start_column: startColumn,
+ end_line: lineIndex,
+ end_column: endColumn,
+ };
+}
+
+/**
+ * Build diagnostics for the whole editor source (multi-line). Each non-empty,
+ * non-comment line is parsed as one Redis command.
+ */
+export function buildRedisSyntaxDiagnostics(source: string): SqlSemanticDiagnostic[] {
+ const diagnostics: SqlSemanticDiagnostic[] = [];
+ const lines = source.split(/\r?\n/);
+
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
+ const rawLine = lines[lineIndex];
+ const lineNo = lineIndex + 1; // 1-based line number for SqlTextSpan
+ if (!rawLine || !rawLine.trim()) continue;
+ // Skip comment-ish lines (Redis has no official comments, but `#`/`--` are
+ // commonly used by users as notes).
+ if (/^\s*(#|--)/.test(rawLine)) continue;
+
+ const { argv, unclosedQuote, unclosedQuoteStart } = tokenizeRedisLine(rawLine);
+
+ if (unclosedQuote) {
+ const startCol = unclosedQuoteStart ?? 1;
+ diagnostics.push({
+ span: lineSpan(lineNo, startCol, Math.max(rawLine.length, startCol)),
+ message: "Unclosed quote",
+ severity: "error",
+ });
+ continue; // further checks are unreliable without a clean parse
+ }
+
+ if (argv.length === 0) continue;
+
+ const upper = argv.map((token) => token.value.toUpperCase());
+ const spec = resolveRedisCommandSpec(upper);
+ const commandToken = argv[0];
+
+ if (!spec) {
+ diagnostics.push({
+ span: lineSpan(lineNo, commandToken.startColumn, commandToken.endColumn),
+ message: `Unknown command '${argv[0].value}'`,
+ severity: "error",
+ });
+ continue;
+ }
+
+ if (!aritySatisfied(spec.arity, argv.length)) {
+ diagnostics.push({
+ span: lineSpan(lineNo, commandToken.startColumn, commandToken.endColumn),
+ message: `Wrong number of arguments for '${argv[0].value}': expected ${describeArity(spec.arity)}, got ${argv.length - 1}`,
+ severity: "error",
+ });
+ // Don't also emit a safety marker on the same token — arity error is clearer.
+ continue;
+ }
+
+ if (spec.safety === "blocked") {
+ diagnostics.push({
+ span: lineSpan(lineNo, commandToken.startColumn, commandToken.endColumn),
+ message: `Blocked command '${argv[0].value}'`,
+ severity: "error",
+ });
+ } else if (spec.safety === "confirm") {
+ diagnostics.push({
+ span: lineSpan(lineNo, commandToken.startColumn, commandToken.endColumn),
+ message: `Write command '${argv[0].value}' — will modify data`,
+ severity: "warning",
+ });
+ }
+ }
+
+ return diagnostics;
+}
+
+/**
+ * Gate diagnostics while the user is actively typing the command name on the
+ * current line, to avoid transient "Unknown command" noise. Mirrors the intent
+ * of `shouldRunSqlSemanticDiagnostics`.
+ */
+export function shouldRunRedisDiagnostics(source: string, cursor: number): boolean {
+ if (!source.trim()) return false;
+ // Find the line the cursor is on.
+ const upto = source.slice(0, cursor);
+ const lineStart = upto.lastIndexOf("\n") + 1;
+ const lineText = source.slice(lineStart, cursor);
+ const trimmed = lineText.trimStart();
+ // If the cursor line only has whitespace and a partial first token with no
+ // separating whitespace yet, we're still typing the command name → wait.
+ if (trimmed.length > 0 && !/\s/.test(trimmed)) return false;
+ return true;
+}
diff --git a/packages/app-tests/redisSyntaxDiagnostics.test.ts b/packages/app-tests/redisSyntaxDiagnostics.test.ts
new file mode 100644
index 0000000000..d5bf86d806
--- /dev/null
+++ b/packages/app-tests/redisSyntaxDiagnostics.test.ts
@@ -0,0 +1,137 @@
+import assert from "node:assert/strict";
+import { test } from "vitest";
+import { buildRedisSyntaxDiagnostics, shouldRunRedisDiagnostics, tokenizeRedisLine } from "../../apps/desktop/src/lib/redisSyntaxDiagnostics.ts";
+
+function messages(source: string): string[] {
+ return buildRedisSyntaxDiagnostics(source).map((d) => d.message);
+}
+
+test("reports no diagnostics for read-only valid commands", () => {
+ assert.deepEqual(messages("GET foo"), []);
+ assert.deepEqual(messages("HGETALL k"), []);
+ assert.deepEqual(messages("SCAN 0"), []);
+});
+
+test("flags unknown command name", () => {
+ const diags = buildRedisSyntaxDiagnostics("GETT foo");
+ assert.equal(diags.length, 1);
+ assert.equal(diags[0].severity, "error");
+ assert.match(diags[0].message, /Unknown command 'GETT'/);
+ // span covers the command-name token on line 1
+ assert.equal(diags[0].span.start_line, 1);
+ assert.equal(diags[0].span.start_column, 1);
+});
+
+test("flags wrong arity (too few arguments)", () => {
+ const diags = buildRedisSyntaxDiagnostics("GET");
+ assert.equal(diags.length, 1);
+ assert.match(diags[0].message, /Wrong number of arguments for 'GET'/);
+ assert.match(diags[0].message, /expected exactly 1 argument/);
+});
+
+test("flags wrong arity (too many arguments)", () => {
+ // GET arity is 2 (exact). Extra args → error.
+ const diags = buildRedisSyntaxDiagnostics("GET a b");
+ assert.equal(diags.length, 1);
+ assert.match(diags[0].message, /Wrong number of arguments for 'GET'/);
+});
+
+test("respects variable arity (negative arity is a minimum)", () => {
+ // MSET arity -3 → at least 2 args; 2 args (3 tokens) is valid (still flagged write-warning).
+ const ok3 = buildRedisSyntaxDiagnostics("MSET k1 v1");
+ assert.equal(ok3.length, 1);
+ assert.equal(ok3[0].severity, "warning");
+ const ok4 = buildRedisSyntaxDiagnostics("MSET k1 v1 k2 v2");
+ assert.equal(ok4.length, 1);
+ assert.equal(ok4[0].severity, "warning");
+ // Too few → arity error takes precedence.
+ const diags = buildRedisSyntaxDiagnostics("MSET k1");
+ assert.equal(diags.length, 1);
+ assert.match(diags[0].message, /Wrong number of arguments for 'MSET'/);
+});
+
+test("flags unclosed quote and spans to end of line", () => {
+ const diags = buildRedisSyntaxDiagnostics('SET "abc b');
+ assert.equal(diags.length, 1);
+ assert.equal(diags[0].severity, "error");
+ assert.match(diags[0].message, /Unclosed quote/);
+ assert.equal(diags[0].span.start_column, 5); // quote starts at column 5
+});
+
+test("highlights write commands as warning", () => {
+ const diags = buildRedisSyntaxDiagnostics("DEL x");
+ assert.equal(diags.length, 1);
+ assert.equal(diags[0].severity, "warning");
+ assert.match(diags[0].message, /Write command 'DEL'/);
+});
+
+test("highlights flushall as blocked error but flushdb as confirm warning", () => {
+ // Aligned with the execution safety classification: FLUSHALL=blocked, FLUSHDB=confirm.
+ const all = buildRedisSyntaxDiagnostics("FLUSHALL");
+ assert.equal(all.length, 1);
+ assert.equal(all[0].severity, "error");
+ assert.match(all[0].message, /Blocked command 'FLUSHALL'/);
+
+ const db = buildRedisSyntaxDiagnostics("FLUSHDB");
+ assert.equal(db.length, 1);
+ assert.equal(db[0].severity, "warning");
+ assert.match(db[0].message, /Write command 'FLUSHDB'/);
+});
+
+test("subcommands resolve via MAIN SUB key", () => {
+ // XGROUP CREATE stream group id MKSTREAM → 6 tokens, satisfies arity -6, confirm → warning.
+ const diags = buildRedisSyntaxDiagnostics("XGROUP CREATE stream group $ MKSTREAM");
+ assert.equal(diags.length, 1);
+ assert.equal(diags[0].severity, "warning");
+ assert.match(diags[0].message, /Write command 'XGROUP'/);
+});
+
+test("treats command names case-insensitively", () => {
+ assert.deepEqual(messages("get foo"), []);
+ const setDiag = buildRedisSyntaxDiagnostics("Set a b");
+ assert.equal(setDiag.length, 1);
+ assert.equal(setDiag[0].severity, "warning");
+ const diags = buildRedisSyntaxDiagnostics("flushall");
+ assert.match(diags[0].message, /Blocked command 'flushall'/);
+});
+
+test("handles multi-line input with per-line diagnostics", () => {
+ const source = "GET ok\nFLUSHALL\nBADCMD x";
+ const diags = buildRedisSyntaxDiagnostics(source);
+ assert.equal(diags.length, 2);
+ const lines = diags.map((d) => d.span.start_line).sort((a, b) => a - b);
+ assert.deepEqual(lines, [2, 3]);
+ assert.match(diags.find((d) => d.span.start_line === 2)!.message, /Blocked/);
+ assert.match(diags.find((d) => d.span.start_line === 3)!.message, /Unknown command/);
+});
+
+test("ignores blank and comment lines", () => {
+ assert.deepEqual(messages(""), []);
+ assert.deepEqual(messages("\n\n"), []);
+ assert.deepEqual(messages("# a note\nGET foo"), []);
+ assert.deepEqual(messages("-- note\nGET foo"), []);
+});
+
+test("strips trailing semicolon terminator", () => {
+ assert.deepEqual(messages("GET foo;"), []);
+});
+
+test("shouldRunRedisDiagnostics waits while typing the command name", () => {
+ // cursor at end of a bare partial token (no whitespace yet) → wait
+ assert.equal(shouldRunRedisDiagnostics("GETT", 4), false);
+ // once a space exists after the command name → run
+ assert.equal(shouldRunRedisDiagnostics("GETT foo", 8), true);
+ assert.equal(shouldRunRedisDiagnostics("", 0), false);
+});
+
+test("tokenizeRedisLine preserves quoted values with spaces", () => {
+ const { argv, unclosedQuote } = tokenizeRedisLine('SET mykey "hello world"');
+ assert.equal(unclosedQuote, false);
+ assert.deepEqual(argv.map((t) => t.value), ["SET", "mykey", "hello world"]);
+ assert.equal(argv[2]!.startColumn, 11);
+});
+
+test("tokenizeRedisLine handles backslash escapes", () => {
+ const { argv } = tokenizeRedisLine('SET k a\\ b');
+ assert.deepEqual(argv.map((t) => t.value), ["SET", "k", "a b"]);
+});