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(editor): suggest identifiers inside quoted prefixes (#12024)

HARRISONb9690840adff
diff --git a/apps/desktop/src/components/editor/__tests__/useQueryEditorCompletion.spec.ts b/apps/desktop/src/components/editor/__tests__/useQueryEditorCompletion.spec.ts
index b381223860..e2dacc1421 100644
--- a/apps/desktop/src/components/editor/__tests__/useQueryEditorCompletion.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/useQueryEditorCompletion.spec.ts
@@ -654,3 +654,59 @@ sf`,
}
}, 8000);
});
+
+describe("quoted identifier completion results (issue #12008)", () => {
+ // The editor hands CodeMirror the replacement span including the opening
+ // quote; CodeMirror then filters labels against that raw span. Quote-prefixed
+ // spans match no identifier label, so the provider must take over filtering
+ // or the menu renders empty even though the candidates are correct.
+ it.each([
+ ["mysql", "SELECT * FROM `test_"],
+ ["postgres", 'SELECT * FROM "test_'],
+ ["sqlserver", "SELECT * FROM [test_"],
+ ] as const)(
+ "returns a self-filtering result for a quoted identifier in %s",
+ async (databaseType, sql) => {
+ vi.useRealTimers();
+ try {
+ // Production runs with semantic completion on; the legacy context path is
+ // a separate code path with its own coverage.
+ const { provide, store } = createHarness({ databaseType, dialect: databaseType, modelValue: sql }, undefined, true);
+ store.lookupLocalCompletionTables.mockReturnValue([{ name: "test_table" }, { name: "other_table" }]);
+ store.listCompletionTables.mockResolvedValue([{ name: "test_table" }, { name: "other_table" }]);
+
+ const result = await provide();
+
+ expect(result).not.toBeNull();
+ // The raw span CodeMirror would match on is quote-prefixed...
+ expect(sql.slice(result!.from)).toBe(sql.slice(sql.lastIndexOf("test_") - 1));
+ // ...so the provider disables CodeMirror's matcher and ranks the matches itself.
+ expect((result as { filter?: boolean }).filter).toBe(false);
+ expect(result!.validFor).toBeUndefined();
+ const labels = result!.options.map((option) => option.label);
+ expect(labels).toContain("test_table");
+ expect(labels).not.toContain("other_table");
+ } finally {
+ vi.useFakeTimers();
+ }
+ },
+ 8000,
+ );
+
+ it("keeps CodeMirror's matcher enabled for a bare identifier prefix", async () => {
+ vi.useRealTimers();
+ try {
+ // INSERT has no independent table-alias candidates that need matcher bypass.
+ const { provide, store } = createHarness({ databaseType: "mysql", dialect: "mysql", modelValue: "INSERT INTO test_" }, undefined, true);
+ store.lookupLocalCompletionTables.mockReturnValue([{ name: "test_table" }]);
+ store.listCompletionTables.mockResolvedValue([{ name: "test_table" }]);
+
+ const result = await provide();
+
+ expect(result).not.toBeNull();
+ expect((result as { filter?: boolean }).filter).toBeUndefined();
+ } finally {
+ vi.useFakeTimers();
+ }
+ }, 8000);
+});
diff --git a/apps/desktop/src/components/editor/useQueryEditorCompletion.ts b/apps/desktop/src/components/editor/useQueryEditorCompletion.ts
index 5e21a10495..d373209a9a 100644
--- a/apps/desktop/src/components/editor/useQueryEditorCompletion.ts
+++ b/apps/desktop/src/components/editor/useQueryEditorCompletion.ts
@@ -14,6 +14,7 @@ import {
isSqlLikeCompletionStatement,
normalizeIdentifierPart,
prepareSqlCompletionReplacement,
+ quotedCompletionFilterPrefix,
recordCompletionSelection,
shouldAutoOpenSqlCompletion,
shouldChainSqlCompletionAfterAccept,
@@ -281,16 +282,23 @@ export function useQueryEditorCompletion(options: QueryEditorCompletionOptions)
return true;
}
- function buildCompletionResult(sourceItems: Array<QueryCompletionItem | BatchColumnSelectionActionItem>, from: number, validFor?: RegExp, prefix?: string) {
+ function buildCompletionResult(sourceItems: Array<QueryCompletionItem | BatchColumnSelectionActionItem>, from: number, validFor?: RegExp, prefix?: string, queryText?: string) {
const items = filterExcludedCompletions(sourceItems, excludedCompletionLabelSet(settingsStore.editorSettings.excludedCompletionItems));
if (items.length === 0) return null;
- const bypassFilter = !!prefix && shouldBypassCompletionFilter(prefix, items);
- const resultItems = bypassFilter && prefix ? completionItemsForBypassedFilter(prefix, items) : items;
+ const matcherBypass = !!prefix && shouldBypassCompletionFilter(prefix, items);
+ // CodeMirror matches each label against `queryText` (the document span from
+ // `from` to the cursor). Inside a quoted identifier that span keeps the
+ // opening quote, so no label ever matches and the menu comes up empty
+ // (#12008). The provider already filtered by the unquoted prefix, so take
+ // over matching for exactly that case, like the Han/pinyin bypass does.
+ const quotedBypassPrefix = prefix && queryText ? quotedCompletionFilterPrefix(queryText, prefix) : undefined;
+ const bypassFilter = matcherBypass || !!quotedBypassPrefix;
+ const resultItems = matcherBypass && prefix ? completionItemsForBypassedFilter(prefix, items) : items;
return {
from,
// Keep CodeMirror's live filtering enabled so an already-open menu follows the typed prefix.
options: resultItems.map((item) => completionOptionForItem(item)),
- validFor,
+ validFor: bypassFilter ? undefined : validFor,
// When bypassing CodeMirror's matcher, supply our own highlight ranges so
// the matched characters (Han substring or pinyin initials) stay marked.
// Ranges must target the rendered text, which is displayLabel when set.
@@ -326,7 +334,7 @@ export function useQueryEditorCompletion(options: QueryEditorCompletionOptions)
},
]
: [];
- return buildCompletionResult(actions.length > 0 ? [...replacement.items, ...actions] : replacement.items, replacement.from, getSqlCompletionResultValidFor(fullDoc, position), completionContext.prefix);
+ return buildCompletionResult(actions.length > 0 ? [...replacement.items, ...actions] : replacement.items, replacement.from, getSqlCompletionResultValidFor(fullDoc, position), completionContext.prefix, fullDoc.slice(replacement.from, position));
}
function itemHasHanText(item: QueryCompletionItem | BatchColumnSelectionActionItem): boolean {
diff --git a/apps/desktop/src/components/mqtt/__tests__/MqttAdminConsolePublishTopic.spec.ts b/apps/desktop/src/components/mqtt/__tests__/MqttAdminConsolePublishTopic.spec.ts
index 3a10f0fdcc..cacd0b3b2f 100644
--- a/apps/desktop/src/components/mqtt/__tests__/MqttAdminConsolePublishTopic.spec.ts
+++ b/apps/desktop/src/components/mqtt/__tests__/MqttAdminConsolePublishTopic.spec.ts
@@ -12,15 +12,13 @@ const { mqttListSavedTopicConfigsMock, mqttGetMessagesMock } = vi.hoisted(() =>
}));
vi.mock("@/lib/backend/api", () => ({
- mqttGetBrokerInfo: vi.fn(
- async (): Promise<MqttBrokerInfo> => ({
- brokerUrl: "mqtt://localhost:1883",
- clientId: "dbx-test",
- connected: true,
- protocolVersion: "5.0",
- subscriptionCount: 1,
- }),
- ),
+ mqttGetBrokerInfo: vi.fn(async (): Promise<MqttBrokerInfo> => ({
+ brokerUrl: "mqtt://localhost:1883",
+ clientId: "dbx-test",
+ connected: true,
+ protocolVersion: "5.0",
+ subscriptionCount: 1,
+ })),
mqttListTopics: vi.fn(async () => [["device/status", "atmostonce"]]),
mqttListSavedTopicConfigs: mqttListSavedTopicConfigsMock,
mqttGetMessages: mqttGetMessagesMock,
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts
index 198c6a4b90..509295d51e 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlCompletion.context.spec.ts
@@ -7,6 +7,7 @@ import {
getPostgresSequenceLiteralCompletionContext,
getSqlCompletionContext,
prepareSqlCompletionReplacement,
+ quotedCompletionFilterPrefix,
selectStarResultColumnsMatch,
shouldAutoOpenSqlCompletion,
} from "@/lib/sql/sqlCompletion";
@@ -2732,3 +2733,30 @@ describe("smart unpaired SQL keyword completion before existing keywords (#11527
expect(keyLabels).not.toContain("UNIQUE KEY");
});
});
+
+describe("quoted identifier completion filtering (issue #12008)", () => {
+ // CodeMirror filters candidate labels against the raw document span from the
+ // completion result's `from` to the cursor. A quoted-identifier completion
+ // replaces the opening quote too, so that span starts with `` ` ``/`"`/`[`
+ // and no identifier label can ever match it, leaving the menu empty.
+ it.each([
+ ["`test_", "test_", "test_"],
+ ['"test_', "test_", "test_"],
+ ["[test_", "test_", "test_"],
+ ["`test_`", "test_", "test_"],
+ ['"test_"', "test_", "test_"],
+ ["[test_]", "test_", "test_"],
+ ])("maps the quoted span %s with prefix %s back to %s", (query, prefix, expected) => {
+ expect(quotedCompletionFilterPrefix(query, prefix)).toBe(expected);
+ });
+
+ it.each([
+ ["test_", "test_"],
+ ["`other_", "test_"],
+ ["`test", "test_"],
+ ["tes", "test_"],
+ ["", "test_"],
+ ])("leaves %s (prefix %s) to CodeMirror's own matcher", (query, prefix) => {
+ expect(quotedCompletionFilterPrefix(query, prefix)).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/lib/sql/sqlCompletion.ts b/apps/desktop/src/lib/sql/sqlCompletion.ts
index 510cb176b4..8c25cb5e3f 100644
--- a/apps/desktop/src/lib/sql/sqlCompletion.ts
+++ b/apps/desktop/src/lib/sql/sqlCompletion.ts
@@ -1678,6 +1678,30 @@ const SQL_COMPLETION_CLOSING_QUOTES: Readonly<Record<string, SqlCompletionClosin
"[": "]",
};
+/**
+ * CodeMirror runs its own matcher over each candidate label against the
+ * document text between the completion result's `from` and the cursor. For a
+ * bare identifier that text is exactly the typed prefix, but a
+ * quoted-identifier completion has to replace the span *including* its opening
+ * quote, so `from` sits on the quote and the text reads `` `test_ `` /`"test_"`/
+ * `[test_`. No identifier label starts with a quote character, so CodeMirror
+ * drops every option and the menu stays empty even though the provider found
+ * matches (#12008).
+ *
+ * The provider already filtered and ranked candidates by the unquoted prefix,
+ * so return that prefix when the only difference is the surrounding quote, and
+ * let the caller bypass CodeMirror's matcher with its own match ranges.
+ * Returns `undefined` when the text is a plain prefix CodeMirror can match.
+ */
+export function quotedCompletionFilterPrefix(query: string, prefix: string): string | undefined {
+ if (!query || !prefix || query === prefix) return undefined;
+ const closing = SQL_COMPLETION_CLOSING_QUOTES[query[0] ?? ""];
+ if (!closing) return undefined;
+ const quotedByClosingQuote = query.length > 1 && query.endsWith(closing);
+ const inner = quotedByClosingQuote ? query.slice(1, -1) : query.slice(1);
+ return inner === prefix ? prefix : undefined;
+}
+
const SELECT_WILDCARD_FOLLOWING_CLAUSES = new Set(["except", "fetch", "for", "from", "group", "having", "intersect", "into", "limit", "offset", "order", "qualify", "union", "where", "window"]);
const SELECT_PROJECTION_MODIFIERS = new Set(["all", "distinct", "distinctrow"]);