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(quick-open): prevent fuzzy matches across metadata fields (#13080)

heeeex100f2e650765b46
diff --git a/apps/desktop/src/components/quick-open/__tests__/QuickOpenDialog.preview.spec.ts b/apps/desktop/src/components/quick-open/__tests__/QuickOpenDialog.preview.spec.ts
index dfcb54196f..a1aaeda224 100644
--- a/apps/desktop/src/components/quick-open/__tests__/QuickOpenDialog.preview.spec.ts
+++ b/apps/desktop/src/components/quick-open/__tests__/QuickOpenDialog.preview.spec.ts
@@ -4,7 +4,7 @@ import { createApp, h, nextTick, reactive, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorView } from "@codemirror/view";
-const mocks = vi.hoisted(() => ({ select: vi.fn(), updateOpen: vi.fn(), read: vi.fn(), write: vi.fn(), toast: vi.fn() }));
+const mocks = vi.hoisted(() => ({ select: vi.fn(), updateOpen: vi.fn(), read: vi.fn(), write: vi.fn(), toast: vi.fn(), folders: [] as string[], listFiles: vi.fn() }));
vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => ({ connections: [], treeNodes: [], connectedIds: new Set() }) }));
vi.mock("@/stores/savedSqlStore", () => ({ useSavedSqlStore: () => ({ allFiles: [] }) }));
vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: { shortcuts: {}, fontSize: 13, fontFamily: "monospace", theme: "app" } }) }));
@@ -19,7 +19,7 @@ vi.mock("@/lib/plugins/pluginCommandPalette", async () => {
});
vi.mock("@/lib/sqlFile/sqlFileFolders", async () => {
const { ref } = await import("vue");
- return { getSqlFileFolderPaths: () => [], getSqlFileFilter: () => "*.sql", sqlFileFoldersVersion: ref(0) };
+ return { getSqlFileFolderPaths: () => mocks.folders, getSqlFileFilter: () => "*.sql", sqlFileFoldersVersion: ref(0) };
});
vi.mock("@/lib/globalSearch/globalSearchSettings", async () => {
const { ref } = await import("vue");
@@ -27,6 +27,7 @@ vi.mock("@/lib/globalSearch/globalSearchSettings", async () => {
});
vi.mock("@/lib/backend/api", () => ({
listPlugins: async () => [],
+ listSqlFilesInFolder: mocks.listFiles,
readExternalSqlFileSnapshot: async (...args: unknown[]) => ({ content: await mocks.read(...args), version: { contentHash: "original", modifiedNs: "1", sizeBytes: 26 }, encoding: "utf8" }),
writeExternalSqlFile: mocks.write,
globalSearch: async () => [
@@ -76,6 +77,8 @@ async function mountSearch() {
}
beforeEach(() => {
+ mocks.folders = [];
+ mocks.listFiles.mockReset().mockResolvedValue([]);
mocks.select.mockReset();
mocks.updateOpen.mockReset();
mocks.read.mockReset().mockResolvedValue("-- heading\nSELECT needle;");
@@ -89,6 +92,56 @@ afterEach(() => {
vi.restoreAllMocks();
});
+describe("object search metadata regression", () => {
+ it("removes false matches and opens the correct file after keyboard navigation", async () => {
+ mocks.folders = ["/order-reports"];
+ const firstName = "report-v2024-07-customer-order-detail-export.sql";
+ const firstPath = `/order-reports/export/${firstName}`;
+ const secondPath = "/order-reports/export/summary.sql";
+ mocks.listFiles.mockResolvedValue([
+ { name: firstName, path: firstPath, is_dir: false, children: [] },
+ { name: "summary.sql", path: secondPath, is_dir: false, children: [] },
+ ]);
+ host = document.createElement("div");
+ document.body.appendChild(host);
+ const props = reactive({ open: false, onSelect: mocks.select, "onUpdate:open": mocks.updateOpen });
+ app = createApp({ render: () => h(QuickOpenDialog, props) });
+ app.use(i18n);
+ app.mount(host);
+ props.open = true;
+ await nextTick();
+ const input = host.querySelector<HTMLInputElement>("input")!;
+ async function search(query: string) {
+ input.value = query;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+ }
+ await vi.waitFor(() => expect(host.querySelectorAll("[data-selected]")).toHaveLength(2));
+ await search("cordetxprep");
+ expect(host.querySelectorAll("[data-selected]")).toHaveLength(0);
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ expect(mocks.select).not.toHaveBeenCalled();
+ await search("cordetxp");
+ expect(host.querySelectorAll("[data-selected]")).toHaveLength(1);
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ expect(mocks.select).toHaveBeenLastCalledWith(expect.objectContaining({ filePath: firstPath, label: firstName }));
+ mocks.select.mockClear();
+ await search("ORDER-REPORTS");
+ const rows = [...host.querySelectorAll<HTMLElement>("[data-selected]")];
+ expect(rows).toHaveLength(2);
+ expect(rows[0].textContent).toContain("summary.sql");
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
+ await nextTick();
+ expect(rows[1].dataset.selected).toBe("true");
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ expect(mocks.select).toHaveBeenLastCalledWith(expect.objectContaining({ filePath: firstPath }));
+ await search("missing-file");
+ expect(host.querySelectorAll("[data-selected]")).toHaveLength(0);
+ await search("summary");
+ expect(host.querySelector('[data-selected="true"]')?.textContent).toContain("summary.sql");
+ });
+});
+
describe("content search preview navigation", () => {
it("pins the preview while editing and resumes navigation after saving", async () => {
const { input, rows, props } = await mountSearch();
diff --git a/apps/desktop/src/composables/__tests__/useQuickOpen.spec.ts b/apps/desktop/src/composables/__tests__/useQuickOpen.spec.ts
index de40c677c1..b12913796b 100644
--- a/apps/desktop/src/composables/__tests__/useQuickOpen.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useQuickOpen.spec.ts
@@ -1,4 +1,4 @@
-import { nextTick } from "vue";
+import { effectScope, nextTick, ref } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { matchQuickOpenText, useQuickOpen } from "@/composables/useQuickOpen";
import * as api from "@/lib/backend/api";
@@ -85,6 +85,122 @@ describe("useQuickOpen", () => {
});
});
+ describe("metadata matching through indexed sources", () => {
+ it.each(["/work/order-reports", "C:\\work\\order-reports"])("filters scanned external files under %s and preserves navigation", async (root) => {
+ vi.mocked(useConnectionStore).mockReturnValue({ connections: [], treeNodes: [] } as any);
+ vi.mocked(getSqlFileFolderPaths).mockReturnValue([root]);
+ const separator = root.includes("\\") ? "\\" : "/";
+ const label = "report-v2024-07-customer-order-detail-export.sql";
+ const path = `${root}${separator}export${separator}${label}`;
+ vi.mocked(api.listSqlFilesInFolder).mockResolvedValue([{ name: "export", path: `${root}${separator}export`, is_dir: true, children: [{ name: label, path, is_dir: false, children: [] }] }]);
+ const scope = effectScope();
+ try {
+ const quickOpen = scope.run(() => useQuickOpen())!;
+ await quickOpen.loadExternalSqlFiles();
+ quickOpen.setQuery("cordetxprep");
+ expect(quickOpen.filteredItems.value).toEqual([]);
+ expect(quickOpen.selectedItem.value).toBeNull();
+ quickOpen.selectNext();
+ expect(quickOpen.selectedItem.value).toBeNull();
+ for (const query of ["ORDER-REPORTS", "export", "cordetxp"]) {
+ quickOpen.setQuery(query);
+ expect(quickOpen.filteredItems.value).toHaveLength(1);
+ expect(quickOpen.selectedItem.value).toMatchObject({ type: "sql_file", filePath: path, description: "order-reports / export" });
+ }
+ expect(quickOpen.selectedItem.value!.matchIndices.map((index) => label[index]).join("")).toBe("cordetxp");
+ quickOpen.setQuery("ORDER-REPORTS");
+ expect(quickOpen.selectedItem.value!.matchIndices).toEqual([]);
+ quickOpen.setQuery(" ");
+ expect(quickOpen.filteredItems.value).toHaveLength(1);
+ } finally {
+ scope.stop();
+ }
+ });
+
+ it("does not combine connection and database characters when finding a table", () => {
+ vi.mocked(useConnectionStore).mockReturnValue({
+ connections: [{ id: "conn1", name: "Production", db_type: "postgres" }],
+ treeNodes: [{ connectionId: "conn1", type: "table", database: "Analytics", schema: "public", label: "用户明细" }],
+ } as any);
+ const { filteredItems, setQuery } = useQuickOpen();
+ setQuery("proana");
+ expect(filteredItems.value).toEqual([]);
+ for (const query of ["PRODUCTION", "Analytics", "PUBLIC"]) {
+ setQuery(query);
+ const table = filteredItems.value.find((item) => item.type === "table");
+ expect(table).toMatchObject({ label: "用户明细", matchIndices: [] });
+ }
+ setQuery("yhmx");
+ expect(filteredItems.value).toHaveLength(1);
+ expect(filteredItems.value[0].matchIndices).toEqual([0, 1, 2, 3]);
+ });
+
+ it("preserves SQL-library connection search without cross-field fuzzy matches", () => {
+ vi.mocked(useConnectionStore).mockReturnValue({ connections: [{ id: "conn1", name: "Production", db_type: "postgres" }], treeNodes: [] } as any);
+ vi.mocked(useSavedSqlStore).mockReturnValue({ ...emptySavedSqlStore(), allFiles: [{ id: "saved1", name: "report.sql", connectionId: "conn1" }] } as any);
+ const { filteredItems, setQuery } = useQuickOpen();
+ setQuery("rptprod");
+ expect(filteredItems.value).toEqual([]);
+ setQuery("Production");
+ expect(filteredItems.value.map((item) => item.type)).toEqual(["connection", "sql_library_file"]);
+ expect(filteredItems.value[1]).toMatchObject({ sqlFileId: "saved1", matchIndices: [] });
+ setQuery("rpt");
+ expect(filteredItems.value[0]).toMatchObject({ type: "sql_library_file", sqlFileId: "saved1", matchIndices: [0, 2, 5] });
+ });
+
+ it("keeps plugin commands searchable by literal description and fuzzy visible label", () => {
+ vi.mocked(useConnectionStore).mockReturnValue({ connections: [], treeNodes: [] } as any);
+ const { filteredItems, setQuery } = useQuickOpen({ extraItems: ref([{ id: "command", type: "plugin_command", label: "Open console", description: "Manage servers", searchText: "Open console Manage servers AdminTools", connectionId: "", pluginId: "admin", commandId: "open" }]) });
+ setQuery("ocms");
+ expect(filteredItems.value).toEqual([]);
+ for (const query of ["manage servers", "ADMINTOOLS"]) {
+ setQuery(query);
+ expect(filteredItems.value).toHaveLength(1);
+ expect(filteredItems.value[0]).toMatchObject({ commandId: "open", matchIndices: [] });
+ }
+ setQuery("oc");
+ expect(filteredItems.value[0].matchIndices).toEqual([0, 5]);
+ });
+ });
+
+ describe("metadata matching", () => {
+ it.each([
+ ["cordetxprep", "report-v2024-07-customer-order-detail-export.sql", "report-v2024-07-customer-order-detail-export.sql export order-reports"],
+ ["sper", "report.sql", "report.sql sales production export reports"],
+ ["salesprod", "report.sql", "report.sql sales production"],
+ ["zzj", "report.sql", "report.sql 总租金"],
+ ])("rejects non-literal metadata matches for %s", (query, label, searchText) => {
+ vi.mocked(useConnectionStore).mockReturnValue({ connections: [], treeNodes: [] } as any);
+ const { filteredItems, setQuery } = useQuickOpen({ extraItems: ref([{ id: "file", type: "sql_file", label, searchText, connectionId: "" }]) });
+ setQuery(query);
+ expect(filteredItems.value).toEqual([]);
+ });
+
+ it.each(["PRODUCTION", "duction", " production "])("preserves literal metadata search for %s below label matches", (query) => {
+ vi.mocked(useConnectionStore).mockReturnValue({ connections: [], treeNodes: [] } as any);
+ const { filteredItems, setQuery } = useQuickOpen({
+ extraItems: ref([
+ { id: "metadata", type: "sql_file", label: "report.sql", searchText: "Production reports", connectionId: "" },
+ { id: "label", type: "sql_file", label: "production.sql", searchText: "production.sql", connectionId: "" },
+ ]),
+ });
+ setQuery(query);
+ expect(filteredItems.value.map((item) => item.id)).toEqual(["label", "metadata"]);
+ expect(filteredItems.value[0].matchIndices.length).toBeGreaterThan(0);
+ expect(filteredItems.value[1].matchIndices).toEqual([]);
+ expect(filteredItems.value[1].matchScore).toBeGreaterThan(1000);
+ });
+
+ it("preserves fuzzy file-name matches and their highlights", () => {
+ vi.mocked(useConnectionStore).mockReturnValue({ connections: [], treeNodes: [] } as any);
+ const label = "report-v2024-07-customer-order-detail-export.sql";
+ const { filteredItems, setQuery } = useQuickOpen({ extraItems: ref([{ id: "file", type: "sql_file", label, searchText: `${label} export order-reports`, connectionId: "" }]) });
+ setQuery("cordetxp");
+ expect(filteredItems.value).toHaveLength(1);
+ expect(filteredItems.value[0].matchIndices.map((index) => label[index]).join("")).toBe("cordetxp");
+ });
+ });
+
describe("fuzzyMatch function", () => {
it("ranks exact names, initials, prefixes, substrings, and fuzzy matches in order", () => {
const exact = matchQuickOpenText("shop", "shop");
diff --git a/apps/desktop/src/composables/useQuickOpen.ts b/apps/desktop/src/composables/useQuickOpen.ts
index b7f966866b..0641da711f 100644
--- a/apps/desktop/src/composables/useQuickOpen.ts
+++ b/apps/desktop/src/composables/useQuickOpen.ts
@@ -278,6 +278,17 @@ export function matchQuickOpenText(query: string, text: string): QuickOpenMatch
return null;
}
+/** Search concatenated metadata literally so matches cannot stitch unrelated fields together. */
+function matchQuickOpenMetadata(query: string, text: string): QuickOpenMatch | null {
+ const lowerQuery = query.trim().toLowerCase();
+ const lowerText = text.toLowerCase();
+ const index = lowerText.indexOf(lowerQuery);
+ if (index < 0) return null;
+ if (lowerText === lowerQuery) return { kind: "exact", score: 1, indices: [] };
+ if (index === 0) return { kind: "prefix", score: 200 + Math.min(text.length - lowerQuery.length, 99), indices: [] };
+ return { kind: "substring", score: 400 + Math.min(index, 99), indices: [] };
+}
+
interface MatchedItem extends QuickOpenItem {
matchScore: number;
matchIndices: number[];
@@ -969,7 +980,7 @@ export function useQuickOpen(options: UseQuickOpenOptions = {}) {
if (seen.has(key)) continue;
seen.add(key);
const labelMatch = matchQuickOpenText(searchQuery.value, item.label);
- const metadataMatch = labelMatch ? null : matchQuickOpenText(searchQuery.value, item.searchText);
+ const metadataMatch = labelMatch ? null : matchQuickOpenMetadata(searchQuery.value, item.searchText);
const result = labelMatch ?? metadataMatch;
if (result) {
matched.push({