feat(grid): add SQL syntax suggestions to WHERE condition editor

This commit is contained in:
lxk955 authored and GitHub committed 2026-10-07 03:08:53 +08:00
1 parent 7530777bac
commit 03b50e167e
4 files changed
+165 -28

No files matched your search

@@ -571,4 +571,57 @@ describe("useDataGridConditionEditor", () => {
expect(editor.handleKeydown(processEnter)).toBeUndefined(); expect(editor.handleKeydown(processEnter)).toBeUndefined();
expect(processEnter.preventDefault).not.toHaveBeenCalled(); 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" }]));
});
}); });
@@ -52,8 +52,41 @@ const WHERE_TOKEN_PATTERN = /([^\s,()><=!&|]+)$/;
const ORDER_BY_TOKEN_PATTERN = /([^\s,()]+)$/; const ORDER_BY_TOKEN_PATTERN = /([^\s,()]+)$/;
const WHERE_TOKEN_FORWARD_PATTERN = /^([^\s,()><=!&|]+)/; const WHERE_TOKEN_FORWARD_PATTERN = /^([^\s,()><=!&|]+)/;
const ORDER_BY_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_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)。 * 否则用户输入值时会看到列名补全、回车/接受后输入被改写(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); 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.insideString) return "none";
if (target.quotedIdentifier) return "field"; if (target.quotedIdentifier) return "field";
const prefix = target.value.slice(0, target.from).trimEnd(); 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"; if (WHERE_VALUE_OPERATOR_PATTERN.test(prefix)) return "none";
// 符号比较运算符之后是值位置:`v_id = v` 时不提示列名,只在 AND/OR 等字段位置提示 // 符号比较运算符之后是值位置:`v_id = v` 时不提示列名,只在 AND/OR 等字段位置提示
if (WHERE_SYMBOLIC_COMPARISON_PATTERN.test(prefix)) return "none"; if (WHERE_SYMBOLIC_COMPARISON_PATTERN.test(prefix)) return "none";
// `mi_id IN (v` / `mi_id IN ('a', v` 同样是值列表,不能提示列名 // `mi_id IN (v` / `mi_id IN ('a', v` 同样是值列表,不能提示列名
if (insideInValueList(target.value, target.from, identifierQuote)) return "none"; 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"; return "connector";
} }
@@ -296,6 +332,27 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
dismiss(); dismiss();
} }
function columnSuggestions(columns: readonly DataGridConditionColumnOption[], normalizedToken: string, target: DataGridConditionCompletionTarget, seen: Set<string>): 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[] { function defaultSuggestions(target: DataGridConditionCompletionTarget): DataGridConditionSuggestion[] {
const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target); const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target);
if (role === "none") return []; if (role === "none") return [];
@@ -304,31 +361,52 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
const suggestions: DataGridConditionSuggestion[] = []; const suggestions: DataGridConditionSuggestion[] = [];
if (role === "field") { if (role === "field") {
const columns = toValue(options.columns) ?? []; const columns = toValue(options.columns) ?? [];
if (normalizedToken && columns.some((column) => (typeof column === "string" ? column : column.name).toLowerCase() === normalizedToken)) return []; return columnSuggestions(columns, normalizedToken, target, seen);
const scored: Array<{ suggestion: DataGridConditionSuggestion; score: number; index: number }> = []; }
let index = 0; if (role === "after_not") {
for (const column of columns) { const columns = toValue(options.columns) ?? [];
const columnValue = typeof column === "string" ? column : column.name; suggestions.push(...columnSuggestions(columns, normalizedToken, target, seen));
if (seen.has(columnValue)) continue; if (normalizedToken) {
seen.add(columnValue); for (const keyword of WHERE_AFTER_NOT_KEYWORDS) {
// Keep the existing prefix/pinyin/substring ranking stable, then append if (!keyword.value.toLowerCase().startsWith(normalizedToken) || keyword.value.toLowerCase() === normalizedToken) continue;
// new camel-initial and ordered-fuzzy matches behind those tiers. suggestions.push({ value: keyword.value, kind: "keyword", ...(keyword.comment ? { comment: keyword.comment } : {}) });
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 suggestions;
return scored.map((entry) => entry.suggestion); }
} else { if (role === "is_value") {
// WHERE 已写完一个表达式时提示连接符;ORDER BY 已写出排序列时提示排序方向。 if (normalizedToken) {
const keywords = options.kind === "where" ? WHERE_CONNECTOR_KEYWORDS : ORDER_BY_DIRECTION_KEYWORDS; 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) { for (const keyword of keywords) {
if (!keyword.toLowerCase().startsWith(normalizedToken) || keyword.toLowerCase() === normalizedToken) continue; const val = typeof keyword === "string" ? keyword : keyword.value;
suggestions.push({ value: keyword, kind: "keyword" }); 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; return suggestions;
} }
@@ -339,7 +417,7 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
try { try {
const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target); const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target);
const values = 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 }) ? 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; : undefined;
// A slower request must never replace suggestions for a newer editor value. // A slower request must never replace suggestions for a newer editor value.
@@ -34,6 +34,12 @@ describe("getDataGridConditionSuggestionPosition", () => {
expect(position.width).toBeLessThanOrEqual(520); 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", () => { test("keeps normal width when suggestions have no comments or are keyword/history entries", () => {
expect( expect(
getDataGridConditionSuggestionPreferredWidth([ getDataGridConditionSuggestionPreferredWidth([
@@ -33,9 +33,9 @@ function textWidthUnits(value: string): number {
} }
export function getDataGridConditionSuggestionPreferredWidth(suggestions: readonly DataGridConditionSuggestionContent[]): number | undefined { 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; 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))); return Math.min(COMMENTED_SUGGESTION_MAX_WIDTH, Math.max(COMMENTED_SUGGESTION_MIN_WIDTH, Math.ceil(longestFieldUnits * 7.5 + 208)));
} }