From 03b50e167ef72bfe2e5e7fb06ab6ec1d74b6278b Mon Sep 17 00:00:00 2001 From: lxk955 <164191365+lxk955@users.noreply.github.com> Date: Wed, 7 Oct 2026 03:08:53 +0800 Subject: [PATCH] feat(grid): add SQL syntax suggestions to WHERE condition editor --- .../useDataGridConditionEditor.spec.ts | 53 +++++++ .../composables/useDataGridConditionEditor.ts | 130 ++++++++++++++---- ...ataGridConditionSuggestionPosition.spec.ts | 6 + .../dataGridConditionSuggestionPosition.ts | 4 +- 4 files changed, 165 insertions(+), 28 deletions(-) diff --git a/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts index df1d9a6db1..8a8b4a99c2 100644 --- a/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts +++ b/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts @@ -571,4 +571,57 @@ describe("useDataGridConditionEditor", () => { expect(editor.handleKeydown(processEnter)).toBeUndefined(); expect(processEnter.preventDefault).not.toHaveBeenCalled(); }); + + it("suggests SQL syntax operators including BETWEEN, LIKE, and IS NULL in WHERE condition (#7989)", async () => { + const value = ref(""); + const editor = useDataGridConditionEditor({ + kind: "where", + value, + columns: ["score", "status", "deleted_at"], + historyScope: {}, + suggestionDebounceMs: 1, + }); + + // 1. 根据 betw 提示 BETWEEN 选项,并展示 BETWEEN ... AND ... 注释 + value.value = "score betw"; + await nextTick(); + await vi.waitFor(() => expect(editor.suggestions.value).toEqual([{ value: "BETWEEN", kind: "keyword", comment: "BETWEEN ... AND ..." }])); + expect(editor.accept()).toBe(true); + expect(value.value).toBe("score BETWEEN"); + + // 2. 根据 li 提示 LIKE + value.value = "score li"; + await nextTick(); + await vi.waitFor(() => expect(editor.suggestions.value).toEqual([{ value: "LIKE", kind: "keyword" }])); + + // 3. 根据 is 提示 IS NULL, IS NOT NULL, IS + value.value = "score is"; + await nextTick(); + await vi.waitFor(() => + expect(editor.suggestions.value).toEqual([ + { value: "IS NULL", kind: "keyword" }, + { value: "IS NOT NULL", kind: "keyword" }, + ]), + ); + + // 4. NOT 之后支持提示 BETWEEN 操作符 + value.value = "score not betw"; + await nextTick(); + await vi.waitFor(() => expect(editor.suggestions.value).toEqual([{ value: "BETWEEN", kind: "keyword", comment: "BETWEEN ... AND ..." }])); + + // 5. IS 之后提示 NULL + value.value = "deleted_at IS nu"; + await nextTick(); + await vi.waitFor(() => expect(editor.suggestions.value).toEqual([{ value: "NULL", kind: "keyword" }])); + + // 6. IS NOT 之后提示 NULL + value.value = "deleted_at IS NOT nu"; + await nextTick(); + await vi.waitFor(() => expect(editor.suggestions.value).toEqual([{ value: "NULL", kind: "keyword" }])); + + // 7. BETWEEN 第一个操作数之后提示 AND 连接符 + value.value = "score BETWEEN 1 a"; + await nextTick(); + await vi.waitFor(() => expect(editor.suggestions.value).toEqual([{ value: "AND", kind: "keyword" }])); + }); }); diff --git a/apps/desktop/src/composables/useDataGridConditionEditor.ts b/apps/desktop/src/composables/useDataGridConditionEditor.ts index a876e0350d..cc15097a85 100644 --- a/apps/desktop/src/composables/useDataGridConditionEditor.ts +++ b/apps/desktop/src/composables/useDataGridConditionEditor.ts @@ -52,8 +52,41 @@ const WHERE_TOKEN_PATTERN = /([^\s,()><=!&|]+)$/; const ORDER_BY_TOKEN_PATTERN = /([^\s,()]+)$/; const WHERE_TOKEN_FORWARD_PATTERN = /^([^\s,()><=!&|]+)/; const ORDER_BY_TOKEN_FORWARD_PATTERN = /^([^\s,()]+)/; +export interface DataGridConditionKeyword { + value: string; + comment?: string; +} + +export const WHERE_SYNTAX_KEYWORDS: readonly DataGridConditionKeyword[] = [ + { value: "AND" }, + { value: "OR" }, + { value: "BETWEEN", comment: "BETWEEN ... AND ..." }, + { value: "NOT BETWEEN", comment: "NOT BETWEEN ... AND ..." }, + { value: "LIKE" }, + { value: "NOT LIKE" }, + { value: "ILIKE" }, + { value: "NOT ILIKE" }, + { value: "IN" }, + { value: "NOT IN" }, + { value: "IS NULL" }, + { value: "IS NOT NULL" }, + { value: "IS" }, + { value: "NOT" }, + { value: "REGEXP" }, + { value: "EXISTS" }, + { value: "NOT EXISTS" }, +]; + +export const WHERE_IS_KEYWORDS: readonly DataGridConditionKeyword[] = [{ value: "NULL" }, { value: "NOT NULL" }, { value: "TRUE" }, { value: "FALSE" }]; + +export const WHERE_IS_NOT_KEYWORDS: readonly DataGridConditionKeyword[] = [{ value: "NULL" }, { value: "TRUE" }, { value: "FALSE" }]; + +export const WHERE_AFTER_NOT_KEYWORDS: readonly DataGridConditionKeyword[] = [{ value: "BETWEEN", comment: "BETWEEN ... AND ..." }, { value: "IN" }, { value: "LIKE" }, { value: "ILIKE" }, { value: "EXISTS" }]; + const WHERE_CONNECTOR_KEYWORDS = ["AND", "OR"] as const; -const WHERE_VALUE_OPERATOR_PATTERN = /(?:^|[\s(])(?:IS(?:\s+NOT)?|(?:NOT\s+)?(?:LIKE|ILIKE|IN|BETWEEN)|SIMILAR\s+TO|REGEXP|RLIKE|GLOB|MATCH)\s*$/i; +const WHERE_IS_NOT_OPERATOR_PATTERN = /(?:^|[\s(])IS\s+NOT$/i; +const WHERE_IS_OPERATOR_PATTERN = /(?:^|[\s(])IS$/i; +const WHERE_VALUE_OPERATOR_PATTERN = /(?:^|[\s(])(?:(?:NOT\s+)?(?:LIKE|ILIKE|IN|BETWEEN)|SIMILAR\s+TO|REGEXP|RLIKE|GLOB|MATCH)\s*$/i; /** * 比较类符号运算符。它们后面同样是「值」位置,不应再提示列名, * 否则用户输入值时会看到列名补全、回车/接受后输入被改写(issue #10595)。 @@ -222,16 +255,19 @@ function insideInValueList(value: string, cursor: number, identifierQuote: strin return /(?:^|[\s(])IN$/i.test(before) || /(?:^|[\s(])NOT\s+IN$/i.test(before); } -function whereSuggestionRole(target: DataGridConditionCompletionTarget, identifierQuote: string | undefined): "field" | "connector" | "none" { +function whereSuggestionRole(target: DataGridConditionCompletionTarget, identifierQuote: string | undefined): "field" | "connector" | "is_value" | "is_not_value" | "after_not" | "none" { if (target.insideString) return "none"; if (target.quotedIdentifier) return "field"; const prefix = target.value.slice(0, target.from).trimEnd(); + if (WHERE_IS_NOT_OPERATOR_PATTERN.test(prefix)) return "is_not_value"; + if (WHERE_IS_OPERATOR_PATTERN.test(prefix)) return "is_value"; if (WHERE_VALUE_OPERATOR_PATTERN.test(prefix)) return "none"; // 符号比较运算符之后是值位置:`v_id = v` 时不提示列名,只在 AND/OR 等字段位置提示 if (WHERE_SYMBOLIC_COMPARISON_PATTERN.test(prefix)) return "none"; // `mi_id IN (v` / `mi_id IN ('a', v` 同样是值列表,不能提示列名 if (insideInValueList(target.value, target.from, identifierQuote)) return "none"; - if (!prefix || /(?:^|\s)(?:AND|OR|NOT)$/i.test(prefix) || /[,(+\-*/~]$/.test(prefix)) return "field"; + if (!prefix || /(?:^|\s)(?:AND|OR)$/i.test(prefix) || /[,(+\-*/~]$/.test(prefix)) return "field"; + if (/(?:^|\s)NOT$/i.test(prefix)) return "after_not"; return "connector"; } @@ -296,6 +332,27 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp dismiss(); } + function columnSuggestions(columns: readonly DataGridConditionColumnOption[], normalizedToken: string, target: DataGridConditionCompletionTarget, seen: Set): DataGridConditionSuggestion[] { + if (normalizedToken && columns.some((column) => (typeof column === "string" ? column : column.name).toLowerCase() === normalizedToken)) return []; + const scored: Array<{ suggestion: DataGridConditionSuggestion; score: number; index: number }> = []; + let index = 0; + for (const column of columns) { + const columnValue = typeof column === "string" ? column : column.name; + if (seen.has(columnValue)) continue; + seen.add(columnValue); + // Keep the existing prefix/pinyin/substring ranking stable, then append + // new camel-initial and ordered-fuzzy matches behind those tiers. + const existingScore = normalizedToken ? pinyinAwareMatchScore(columnValue, normalizedToken) : 0; + if (existingScore < 0 && !matchesIdentifierSearch(columnValue, normalizedToken)) continue; + const score = existingScore < 0 ? 50 : existingScore; + const comment = normalizedColumnComment(column); + const insertText = target.quotedIdentifier ? columnValue : typeof column === "string" ? columnValue : column.insertText; + scored.push({ suggestion: { value: columnValue, kind: "column", ...(insertText !== undefined && insertText !== columnValue ? { insertText } : {}), ...(comment ? { comment } : {}) }, score, index: index++ }); + } + scored.sort((a, b) => b.score - a.score || a.index - b.index); + return scored.map((entry) => entry.suggestion); + } + function defaultSuggestions(target: DataGridConditionCompletionTarget): DataGridConditionSuggestion[] { const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target); if (role === "none") return []; @@ -304,31 +361,52 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp const suggestions: DataGridConditionSuggestion[] = []; if (role === "field") { const columns = toValue(options.columns) ?? []; - if (normalizedToken && columns.some((column) => (typeof column === "string" ? column : column.name).toLowerCase() === normalizedToken)) return []; - const scored: Array<{ suggestion: DataGridConditionSuggestion; score: number; index: number }> = []; - let index = 0; - for (const column of columns) { - const columnValue = typeof column === "string" ? column : column.name; - if (seen.has(columnValue)) continue; - seen.add(columnValue); - // Keep the existing prefix/pinyin/substring ranking stable, then append - // new camel-initial and ordered-fuzzy matches behind those tiers. - const existingScore = normalizedToken ? pinyinAwareMatchScore(columnValue, normalizedToken) : 0; - if (existingScore < 0 && !matchesIdentifierSearch(columnValue, normalizedToken)) continue; - const score = existingScore < 0 ? 50 : existingScore; - const comment = normalizedColumnComment(column); - const insertText = target.quotedIdentifier ? columnValue : typeof column === "string" ? columnValue : column.insertText; - scored.push({ suggestion: { value: columnValue, kind: "column", ...(insertText !== undefined && insertText !== columnValue ? { insertText } : {}), ...(comment ? { comment } : {}) }, score, index: index++ }); + return columnSuggestions(columns, normalizedToken, target, seen); + } + if (role === "after_not") { + const columns = toValue(options.columns) ?? []; + suggestions.push(...columnSuggestions(columns, normalizedToken, target, seen)); + if (normalizedToken) { + for (const keyword of WHERE_AFTER_NOT_KEYWORDS) { + if (!keyword.value.toLowerCase().startsWith(normalizedToken) || keyword.value.toLowerCase() === normalizedToken) continue; + suggestions.push({ value: keyword.value, kind: "keyword", ...(keyword.comment ? { comment: keyword.comment } : {}) }); + } } - scored.sort((a, b) => b.score - a.score || a.index - b.index); - return scored.map((entry) => entry.suggestion); - } else { - // WHERE 已写完一个表达式时提示连接符;ORDER BY 已写出排序列时提示排序方向。 - const keywords = options.kind === "where" ? WHERE_CONNECTOR_KEYWORDS : ORDER_BY_DIRECTION_KEYWORDS; + return suggestions; + } + if (role === "is_value") { + if (normalizedToken) { + for (const keyword of WHERE_IS_KEYWORDS) { + if (!keyword.value.toLowerCase().startsWith(normalizedToken) || keyword.value.toLowerCase() === normalizedToken) continue; + suggestions.push({ value: keyword.value, kind: "keyword", ...(keyword.comment ? { comment: keyword.comment } : {}) }); + } + } + return suggestions; + } + if (role === "is_not_value") { + if (normalizedToken) { + for (const keyword of WHERE_IS_NOT_KEYWORDS) { + if (!keyword.value.toLowerCase().startsWith(normalizedToken) || keyword.value.toLowerCase() === normalizedToken) continue; + suggestions.push({ value: keyword.value, kind: "keyword", ...(keyword.comment ? { comment: keyword.comment } : {}) }); + } + } + return suggestions; + } + if (options.kind === "where") { + // WHERE 已写完一个表达式时提示连接符;在列或操作符位置提示 SQL 语法及连接符 + const keywords = normalizedToken ? WHERE_SYNTAX_KEYWORDS : WHERE_CONNECTOR_KEYWORDS; for (const keyword of keywords) { - if (!keyword.toLowerCase().startsWith(normalizedToken) || keyword.toLowerCase() === normalizedToken) continue; - suggestions.push({ value: keyword, kind: "keyword" }); + const val = typeof keyword === "string" ? keyword : keyword.value; + const comment = typeof keyword === "string" ? undefined : keyword.comment; + if (!val.toLowerCase().startsWith(normalizedToken) || val.toLowerCase() === normalizedToken) continue; + suggestions.push({ value: val, kind: "keyword", ...(comment ? { comment } : {}) }); } + return suggestions; + } + // ORDER BY 已写出排序列时提示排序方向。 + for (const keyword of ORDER_BY_DIRECTION_KEYWORDS) { + if (!keyword.toLowerCase().startsWith(normalizedToken) || keyword.toLowerCase() === normalizedToken) continue; + suggestions.push({ value: keyword, kind: "keyword" }); } return suggestions; } @@ -339,7 +417,7 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp try { const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target); const values = - options.suggestionProvider && target.token && role === "field" + options.suggestionProvider && target.token && (role === "field" || role === "after_not") ? await options.suggestionProvider({ kind: options.kind, value: target.value, valueBeforeCursor: target.valueBeforeCursor, token: target.token, from: target.from, to: target.to, selectionStart: target.selectionStart, selectionEnd: target.selectionEnd, signal: controller.signal }) : undefined; // A slower request must never replace suggestions for a newer editor value. diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridConditionSuggestionPosition.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridConditionSuggestionPosition.spec.ts index 3f0c82704c..39278af74d 100644 --- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridConditionSuggestionPosition.spec.ts +++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridConditionSuggestionPosition.spec.ts @@ -34,6 +34,12 @@ describe("getDataGridConditionSuggestionPosition", () => { expect(position.width).toBeLessThanOrEqual(520); }); + test("widens commented keyword suggestions within the configured maximum", () => { + const preferredWidth = getDataGridConditionSuggestionPreferredWidth([{ value: "BETWEEN", kind: "keyword", comment: "BETWEEN ... AND ..." }]); + expect(preferredWidth).toBeGreaterThanOrEqual(360); + expect(preferredWidth).toBeLessThanOrEqual(520); + }); + test("keeps normal width when suggestions have no comments or are keyword/history entries", () => { expect( getDataGridConditionSuggestionPreferredWidth([ diff --git a/apps/desktop/src/lib/dataGrid/dataGridConditionSuggestionPosition.ts b/apps/desktop/src/lib/dataGrid/dataGridConditionSuggestionPosition.ts index 71e5e6f8db..9eba8ffa68 100644 --- a/apps/desktop/src/lib/dataGrid/dataGridConditionSuggestionPosition.ts +++ b/apps/desktop/src/lib/dataGrid/dataGridConditionSuggestionPosition.ts @@ -33,9 +33,9 @@ function textWidthUnits(value: string): number { } export function getDataGridConditionSuggestionPreferredWidth(suggestions: readonly DataGridConditionSuggestionContent[]): number | undefined { - const hasComment = suggestions.some((suggestion) => suggestion.kind === "column" && !!suggestion.comment?.trim()); + const hasComment = suggestions.some((suggestion) => (suggestion.kind === "column" || suggestion.kind === "keyword") && !!suggestion.comment?.trim()); if (!hasComment) return undefined; - const longestFieldUnits = suggestions.reduce((longest, suggestion) => (suggestion.kind === "column" ? Math.max(longest, textWidthUnits(suggestion.value)) : longest), 0); + const longestFieldUnits = suggestions.reduce((longest, suggestion) => (suggestion.kind === "column" || suggestion.kind === "keyword" ? Math.max(longest, textWidthUnits(suggestion.value)) : longest), 0); return Math.min(COMMENTED_SUGGESTION_MAX_WIDTH, Math.max(COMMENTED_SUGGESTION_MIN_WIDTH, Math.ceil(longestFieldUnits * 7.5 + 208))); }