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。

fix(grid): stop filter autocomplete inserting column names

高桥凉介aff43d7ba9ca
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridConditionEditor.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridConditionEditor.spec.ts
index 8219479c17..8ee9a8e8e0 100644
--- a/apps/desktop/src/components/grid/__tests__/DataGridConditionEditor.spec.ts
+++ b/apps/desktop/src/components/grid/__tests__/DataGridConditionEditor.spec.ts
@@ -277,19 +277,20 @@ describe("DataGridConditionEditor quote completion", () => {
});
it("passes the textarea caret range through when accepting a suggestion", async () => {
- const { value, input } = mountEditor("where", "status = cus AND enabled = 1", { columns: ["customer_id"] });
+ const { value, input } = mountEditor("where", "", { columns: ["customer_id"] });
input.focus();
- input.setSelectionRange(12, 12);
- input.dispatchEvent(new Event("select", { bubbles: true }));
+ input.value = "status = 1 AND cus";
+ input.setSelectionRange(18, 18);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
await vi.waitFor(() => expect(document.querySelector('[role="option"]')?.textContent).toContain("customer_id"));
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }));
await nextTick();
- expect(value.value).toBe("status = customer_id AND enabled = 1");
- expect(input.selectionStart).toBe(20);
- expect(input.selectionEnd).toBe(20);
+ expect(value.value).toBe("status = 1 AND customer_id");
+ expect(input.selectionStart).toBe(26);
+ expect(input.selectionEnd).toBe(26);
});
it("starts without an active suggestion and selects the first item on ArrowDown", async () => {
@@ -312,7 +313,7 @@ describe("DataGridConditionEditor quote completion", () => {
expect(value.value).toBe("name");
});
- it("selects the first WHERE field suggestion with Enter", async () => {
+ it("keeps the first WHERE field suggestion unselected and only applies on Enter", async () => {
const { value, input } = mountEditor("where", "", { columns: ["customer_id", "customer_name"] });
input.focus();
input.value = "cus";
@@ -320,11 +321,13 @@ describe("DataGridConditionEditor quote completion", () => {
input.dispatchEvent(new Event("input", { bubbles: true }));
await vi.waitFor(() => expect(document.querySelectorAll('[role="option"]')).toHaveLength(2));
- expect(document.querySelector('[role="option"][aria-selected="true"]')?.textContent).toContain("customer_id");
+ // 不再默认高亮:回车只用于应用筛选,不会把列名写进输入框(issue #10595)
+ expect(document.querySelector('[role="option"][aria-selected="true"]')).toBeNull();
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
await nextTick();
- expect(value.value).toBe("customer_id");
+ expect(value.value).toBe("cus");
+ expect(document.querySelector('[role="listbox"]')).toBeNull();
});
it("does not select a suggestion just because the dropdown appears under the mouse", async () => {
@@ -361,8 +364,8 @@ describe("DataGridConditionEditor quote completion", () => {
it("keeps suggestions closed after Enter applies a complete condition", async () => {
const { input } = mountEditor("where", "", { columns: ["id", "order0", "status"] });
input.focus();
- input.value = "id > 0";
- input.setSelectionRange(6, 6);
+ input.value = "order";
+ input.setSelectionRange(5, 5);
input.dispatchEvent(new Event("input", { bubbles: true }));
await vi.waitFor(() => expect(document.querySelectorAll('[role="option"]')).toHaveLength(1));
diff --git a/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts
index bfa92cdada..df1d9a6db1 100644
--- a/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts
@@ -21,8 +21,8 @@ describe("useDataGridConditionEditor", () => {
vi.useRealTimers();
});
- it("replaces the active token and supports clamped keyboard navigation", async () => {
- const value = ref("status = cus");
+ it("replaces the active field token and supports clamped keyboard navigation", async () => {
+ const value = ref("status = 1 AND cus");
const editor = useDataGridConditionEditor({
kind: "where",
value,
@@ -30,16 +30,94 @@ describe("useDataGridConditionEditor", () => {
historyScope: {},
});
- value.value = "status = cust";
+ value.value = "status = 1 AND cust";
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["customer_id", "customer_name"]));
+ // 不再默认高亮第一条建议:必须显式导航/接受,避免回车应用筛选时改写输入(issue #10595)
+ expect(editor.highlightedIndex.value).toBe(-1);
+ expect(editor.navigate(1)).toBe(true);
expect(editor.highlightedIndex.value).toBe(0);
expect(editor.navigate(1)).toBe(true);
expect(editor.highlightedIndex.value).toBe(1);
expect(editor.navigate(1)).toBe(true);
expect(editor.highlightedIndex.value).toBe(1);
expect(editor.accept()).toBe(true);
- expect(value.value).toBe("status = customer_name");
+ expect(value.value).toBe("status = 1 AND customer_name");
+ });
+
+ it("does not suggest column names while typing a value after a comparison operator", async () => {
+ const value = ref("");
+ const editor = useDataGridConditionEditor({
+ kind: "where",
+ value,
+ columns: ["v_id", "v_name"],
+ historyScope: {},
+ suggestionDebounceMs: 1,
+ });
+
+ // 用户场景:`v_id = v` 时正在输入值,不应该看到列名补全(issue #10595)
+ value.value = "v_id = v";
+ await nextTick();
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ expect(editor.suggestions.value).toEqual([]);
+
+ value.value = "v_id <> v";
+ await nextTick();
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ expect(editor.suggestions.value).toEqual([]);
+
+ // AND 之后是字段位置,仍然提示列名
+ value.value = "v_id = 'x' AND v";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["v_id", "v_name"]));
+ });
+
+ it("does not suggest column names inside an IN value list", async () => {
+ const value = ref("");
+ const editor = useDataGridConditionEditor({
+ kind: "where",
+ value,
+ columns: ["mi_id", "model_name"],
+ historyScope: {},
+ suggestionDebounceMs: 1,
+ });
+
+ // 用户场景:`v_id = v AND mi_id in (v` —— 正在输入 IN 列表里的值(issue #10595)
+ value.value = "v_id = v AND mi_id in (v";
+ await nextTick();
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ expect(editor.suggestions.value).toEqual([]);
+
+ // 列表里的第二个值同样不应提示列名
+ value.value = "mi_id in ('a', m";
+ await nextTick();
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ expect(editor.suggestions.value).toEqual([]);
+
+ // 括号闭合后的新条件仍应提示列名
+ value.value = "mi_id in (1, 2) AND m";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["mi_id", "model_name"]));
+
+ // 裸括号(表达式开头)仍属于字段位置
+ value.value = "(m";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["mi_id", "model_name"]));
+ });
+
+ it("only suggests sort direction after an ORDER BY column", async () => {
+ const value = ref("");
+ const editor = useDataGridConditionEditor({ kind: "orderBy", value, columns: ["create_time", "create_by"], historyScope: {}, suggestionDebounceMs: 1 });
+
+ // 输入 `asc` 时不应提示列名(否则按 Tab 会把列名写进输入框)
+ value.value = "create_time a";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value).toEqual([{ value: "ASC", kind: "keyword" }]));
+
+ // 逗号之后是新的排序列位置,提示列名
+ value.value = "create_time ASC, c";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["create_time", "create_by"]));
});
it.each(["where", "orderBy"] as const)("searches %s fields by camel-case initials and any-position text", async (kind) => {
@@ -108,16 +186,16 @@ describe("useDataGridConditionEditor", () => {
historyScope: {},
});
- value.value = "status = cus AND enabled = 1";
- selectionStart.value = 12;
- selectionEnd.value = 12;
+ value.value = "status = 1 AND cus AND enabled = 2";
+ selectionStart.value = 18;
+ selectionEnd.value = 18;
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["customer_id", "customer_name"]));
expect(editor.accept(0)).toBe(true);
- expect(value.value).toBe("status = customer_id AND enabled = 1");
- expect(selectionStart.value).toBe(20);
- expect(selectionEnd.value).toBe(20);
+ expect(value.value).toBe("status = 1 AND customer_id AND enabled = 2");
+ expect(selectionStart.value).toBe(26);
+ expect(selectionEnd.value).toBe(26);
});
it("uses the current selection as an explicit replacement range", async () => {
@@ -126,14 +204,14 @@ describe("useDataGridConditionEditor", () => {
const selectionEnd = ref(0);
const editor = useDataGridConditionEditor({ kind: "where", value, selectionStart, selectionEnd, columns: ["old_value"], historyScope: {} });
- value.value = "status = old AND enabled = 1";
- selectionStart.value = 9;
- selectionEnd.value = 12;
+ value.value = "old = 1";
+ selectionStart.value = 0;
+ selectionEnd.value = 3;
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["old_value"]));
expect(editor.accept()).toBe(true);
- expect(value.value).toBe("status = old_value AND enabled = 1");
+ expect(value.value).toBe("old_value = 1");
});
it("suggests WHERE connectors after a completed expression", async () => {
@@ -168,7 +246,7 @@ describe("useDataGridConditionEditor", () => {
expect(value.value).toBe("status = 'active' AND owner_id");
});
- it("does not offer connectors inside quoted values or in ORDER BY", async () => {
+ it("does not offer connectors inside quoted values, and offers only sort direction after an ORDER BY column", async () => {
const whereValue = ref("");
const whereEditor = useDataGridConditionEditor({ kind: "where", value: whereValue, columns: ["name"], historyScope: {} });
whereValue.value = "name = 'Alice a";
@@ -179,7 +257,8 @@ describe("useDataGridConditionEditor", () => {
const orderByEditor = useDataGridConditionEditor({ kind: "orderBy", value: orderByValue, columns: ["amount"], historyScope: {} });
orderByValue.value = "created_at a";
await nextTick();
- await vi.waitFor(() => expect(orderByEditor.suggestions.value).toEqual([]));
+ // ORDER BY 的排序列之后是排序方向位置:只提示 ASC/DESC,绝不插入列名(issue #10595)
+ await vi.waitFor(() => expect(orderByEditor.suggestions.value).toEqual([{ value: "ASC", kind: "keyword" }]));
});
it.each(["deleted_at IS ", "deleted_at IS a", "deleted_at IS NOT o", "name LIKE o", "id IN a", "score BETWEEN o"])("does not offer connectors while the keyword operator is incomplete: %s", async (condition) => {
@@ -282,12 +361,12 @@ describe("useDataGridConditionEditor", () => {
historyScope: {},
});
- value.value = kind === "where" ? "status = Order" : "created_at DESC, Order";
+ value.value = kind === "where" ? "status = 1 AND Order" : "created_at DESC, Order";
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value).toEqual([{ value: "OrderId", insertText: '"OrderId"', kind: "column", comment: "Mixed-case identifier" }]));
expect(editor.accept()).toBe(true);
- expect(value.value).toBe(kind === "where" ? 'status = "OrderId"' : 'created_at DESC, "OrderId"');
+ expect(value.value).toBe(kind === "where" ? 'status = 1 AND "OrderId"' : 'created_at DESC, "OrderId"');
});
it("restores quoted history verbatim instead of quoting it again", () => {
@@ -371,21 +450,21 @@ describe("useDataGridConditionEditor", () => {
const suggestionProvider = vi.fn(() => ["customer_id"]);
useDataGridConditionEditor({ kind: "where", value, selectionStart, selectionEnd, historyScope: {}, suggestionProvider });
- value.value = "status = cus AND enabled = 1";
- selectionStart.value = 12;
- selectionEnd.value = 12;
+ value.value = "status = 1 AND cus";
+ selectionStart.value = 18;
+ selectionEnd.value = 18;
await nextTick();
await vi.waitFor(() => expect(suggestionProvider).toHaveBeenCalledOnce());
expect(suggestionProvider).toHaveBeenCalledWith(
expect.objectContaining({
- value: "status = cus AND enabled = 1",
- valueBeforeCursor: "status = cus",
+ value: "status = 1 AND cus",
+ valueBeforeCursor: "status = 1 AND cus",
token: "cus",
- from: 9,
- to: 12,
- selectionStart: 12,
- selectionEnd: 12,
+ from: 15,
+ to: 18,
+ selectionStart: 18,
+ selectionEnd: 18,
}),
);
});
diff --git a/apps/desktop/src/composables/useDataGridConditionEditor.ts b/apps/desktop/src/composables/useDataGridConditionEditor.ts
index f34208c6f7..a876e0350d 100644
--- a/apps/desktop/src/composables/useDataGridConditionEditor.ts
+++ b/apps/desktop/src/composables/useDataGridConditionEditor.ts
@@ -54,6 +54,13 @@ const WHERE_TOKEN_FORWARD_PATTERN = /^([^\s,()><=!&|]+)/;
const ORDER_BY_TOKEN_FORWARD_PATTERN = /^([^\s,()]+)/;
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;
+/**
+ * 比较类符号运算符。它们后面同样是「值」位置,不应再提示列名,
+ * 否则用户输入值时会看到列名补全、回车/接受后输入被改写(issue #10595)。
+ */
+const WHERE_SYMBOLIC_COMPARISON_PATTERN = /(?:<>|!=|<=|>=|=|<|>)$/;
+/** ORDER BY 中排序列之后的位置只应提示排序方向。 */
+const ORDER_BY_DIRECTION_KEYWORDS = ["ASC", "DESC"] as const;
interface DataGridConditionCompletionTarget {
value: string;
@@ -173,15 +180,71 @@ function conditionCompletionTarget(kind: DataGridConditionHistoryKind, value: st
};
}
-function whereSuggestionRole(target: DataGridConditionCompletionTarget): "field" | "connector" | "none" {
+/**
+ * 判断光标是否位于 `IN (...)` 的值列表里(括号由 IN / NOT IN 打开且尚未闭合)。
+ *
+ * `IN (` 之后要输入的是值列表而不是列名;但裸括号(`WHERE (v`)和函数参数里的逗号
+ * 仍然属于"表达式/字段"位置,所以必须区分括号是谁打开的(issue #10595)。
+ */
+function insideInValueList(value: string, cursor: number, identifierQuote: string | undefined): boolean {
+ const identifierOpen = normalizedIdentifierQuote(identifierQuote);
+ const identifierClose = identifierOpen ? identifierCloseQuote(identifierOpen) : undefined;
+ let stringQuote: string | undefined;
+ const openParens: number[] = [];
+ for (let index = 0; index < cursor; index += 1) {
+ const character = value[index];
+ if (stringQuote) {
+ if (character === "\\") {
+ index += 1;
+ } else if (value.startsWith(stringQuote + stringQuote, index)) {
+ index += 1;
+ } else if (character === stringQuote) {
+ stringQuote = undefined;
+ }
+ continue;
+ }
+ if (identifierOpen && value.startsWith(identifierOpen, index)) {
+ index += identifierClose!.length - 1;
+ continue;
+ }
+ if (character === "'" || character === '"') {
+ stringQuote = character;
+ } else if (character === "(") {
+ openParens.push(index);
+ } else if (character === ")") {
+ openParens.pop();
+ }
+ }
+
+ const openIndex = openParens[openParens.length - 1];
+ if (openIndex === undefined) return false;
+ const before = value.slice(0, openIndex).trimEnd();
+ return /(?:^|[\s(])IN$/i.test(before) || /(?:^|[\s(])NOT\s+IN$/i.test(before);
+}
+
+function whereSuggestionRole(target: DataGridConditionCompletionTarget, identifierQuote: string | undefined): "field" | "connector" | "none" {
if (target.insideString) return "none";
if (target.quotedIdentifier) return "field";
const prefix = target.value.slice(0, target.from).trimEnd();
if (WHERE_VALUE_OPERATOR_PATTERN.test(prefix)) return "none";
- if (!prefix || /(?:^|\s)(?:AND|OR|NOT)$/i.test(prefix) || /[,(<>=!~+\-*/]$/.test(prefix)) return "field";
+ // 符号比较运算符之后是值位置:`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";
return "connector";
}
+/**
+ * ORDER BY 的角色判定:开头或逗号之后是排序列位置(提示列名),
+ * 已经写出排序列之后是排序方向位置(提示 ASC/DESC)。
+ * 否则在输入 `asc` 时按 Tab 会把列名插进输入框(issue #10595)。
+ */
+function orderBySuggestionRole(target: DataGridConditionCompletionTarget): "field" | "direction" {
+ const prefix = target.value.slice(0, target.from).trimEnd();
+ return !prefix || prefix.endsWith(",") ? "field" : "direction";
+}
+
export interface DataGridConditionQuoteCompletion {
value: string;
selectionStart: number;
@@ -234,7 +297,7 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
}
function defaultSuggestions(target: DataGridConditionCompletionTarget): DataGridConditionSuggestion[] {
- const role = options.kind === "where" ? whereSuggestionRole(target) : "field";
+ const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target);
if (role === "none") return [];
const normalizedToken = target.token.toLowerCase();
const seen = new Set<string>();
@@ -260,7 +323,9 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
scored.sort((a, b) => b.score - a.score || a.index - b.index);
return scored.map((entry) => entry.suggestion);
} else {
- for (const keyword of WHERE_CONNECTOR_KEYWORDS) {
+ // WHERE 已写完一个表达式时提示连接符;ORDER BY 已写出排序列时提示排序方向。
+ const keywords = options.kind === "where" ? WHERE_CONNECTOR_KEYWORDS : ORDER_BY_DIRECTION_KEYWORDS;
+ for (const keyword of keywords) {
if (!keyword.toLowerCase().startsWith(normalizedToken) || keyword.toLowerCase() === normalizedToken) continue;
suggestions.push({ value: keyword, kind: "keyword" });
}
@@ -272,7 +337,7 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
if (!target.token && (options.kind !== "where" || !target.value.trim())) return;
suggestionsLoading.value = true;
try {
- const role = options.kind === "where" ? whereSuggestionRole(target) : "field";
+ const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target);
const values =
options.suggestionProvider && target.token && role === "field"
? 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 })
@@ -283,7 +348,9 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
const providerValues = values ? [...new Set(values)] : undefined;
suggestions.value = providerValues ? (providerValues.some((value) => value.toLowerCase() === target.token.toLowerCase()) ? [] : providerValues.slice(0, limit).map((suggestion) => ({ value: suggestion, kind: "column" }))) : defaultSuggestions(target).slice(0, limit);
replacementRange.value = { from: target.from, to: target.to };
- highlightedIndex.value = options.kind === "where" && suggestions.value[0]?.kind === "column" ? 0 : -1;
+ // 不再默认高亮第一条建议:否则用户按回车«应用筛选»时会先把高亮项写进输入框(issue #10595)。
+ // 接受补全需要显式操作(↓/↑ 后回车、Tab 或点击)。
+ highlightedIndex.value = -1;
} catch (error) {
if (!controller.signal.aborted && requestId === suggestionRequestId) {
suggestions.value = [];