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。

feat(sql-file): match file contents in the SQL file panel search

Abeautifulsnowb266c53cb801
diff --git a/apps/desktop/src/components/layout/SqlFilePanel.vue b/apps/desktop/src/components/layout/SqlFilePanel.vue
index 7f6fd4c084..370e2cade3 100644
--- a/apps/desktop/src/components/layout/SqlFilePanel.vue
+++ b/apps/desktop/src/components/layout/SqlFilePanel.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
-import { ref, computed, nextTick, onMounted, watch, useId } from "vue";
+import { ref, computed, nextTick, onMounted, onUnmounted, watch, useId } from "vue";
import { useI18n } from "vue-i18n";
-import { FolderOpen, FolderClosed, FileCode, FolderPlus, ChevronRight, ChevronDown, X, Trash2, RefreshCw, FolderSearch, Copy, Play, ChevronsUpDown, ChevronsDownUp, Settings, FilePlus, Pencil, Search, ArrowDownAZ, ArrowUpAZ } from "@lucide/vue";
+import { FolderOpen, FolderClosed, FileCode, FolderPlus, ChevronRight, ChevronDown, X, Trash2, RefreshCw, FolderSearch, Copy, Play, ChevronsUpDown, ChevronsDownUp, Settings, FilePlus, Pencil, Search, ArrowDownAZ, ArrowUpAZ, Loader2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -19,10 +19,13 @@ import { translateBackendError } from "@/i18n/backend-errors";
import { copyToClipboard } from "@/lib/common/clipboard";
import { forgetExternalSqlFileTarget, forgetExternalSqlFolderTargets, moveExternalSqlFileTarget, moveExternalSqlFolderTargets, resolveExternalSqlFileTargetForActiveTab } from "@/lib/sql/externalSqlFileTarget";
import { externalSqlFileOpenErrorMessage, externalSqlEditorMaxBytes, formatSqlFileSize, isExternalSqlFileTooLargeError, isSqlFilePath, normalizeExternalSqlPath, relocateExternalSqlPathWithinFolder } from "@/lib/sql/sqlFileOpen";
+import type { SavedSqlLineMatch } from "@/lib/savedSql/savedSqlSearch";
import * as api from "@/lib/backend/api";
import type { SqlFileEntry } from "@/lib/backend/api";
import { getSqlFileFilter, getSqlFileFolderPaths, saveSqlFileFilter, saveSqlFileFolderPaths, notifySqlFileFoldersChanged } from "@/lib/sqlFile/sqlFileFolders";
import { filterAndSortSqlFileEntries, getSqlFileSortOrder, saveSqlFileSortOrder, type SqlFileSortOrder } from "@/lib/sql/sqlFileTreeFilter";
+import { contentMatchPathSet, searchSqlFileContents, SQL_FILE_CONTENT_SEARCH_DEBOUNCE_MS, type SqlFileContentMatchGroup, type SqlFileContentSearchResult } from "@/lib/sql/sqlFileContentSearch";
+import SqlSearchMatchSnippet from "@/components/layout/SqlSearchMatchSnippet.vue";
import { orderedListSelectionIntent, type OrderedListSelectionItem } from "@/lib/selection/orderedListSelection";
import { getSqlFileOpenMode, saveSqlFileOpenMode, type SqlFileOpenMode } from "@/lib/sqlFile/sqlFileInteraction";
@@ -46,6 +49,9 @@ interface FolderState {
}
const folders = ref<FolderState[]>([]);
+// Bumped whenever the loaded file set changes (folder added/removed/reloaded),
+// so an active content search can be re-run against the new tree.
+const foldersRevision = ref(0);
const fileTree = ref<HTMLElement | null>(null);
const locatingFile = ref(false);
const currentFilePath = computed(() => {
@@ -65,10 +71,181 @@ const searchQuery = computed(() => searchText.value.trim().toLowerCase());
const sortOrder = ref<SqlFileSortOrder>(getSqlFileSortOrder ? getSqlFileSortOrder() : "asc");
const userCollapsedDuringSearch = ref<Set<string>>(new Set());
-watch(searchQuery, () => {
+// ---- content search ------------------------------------------------------
+// Name/dir filtering stays synchronous against the already-loaded tree; body
+// matches come from the backend after a debounce. Only the latest generation
+// may write results, so fast typing cannot apply an older query's hits.
+const contentSearchResult = ref<SqlFileContentSearchResult | null>(null);
+const contentSearching = ref(false);
+// True from the moment a query is scheduled until its backend answer (or
+// failure) lands. The tree uses it to hold back the "no results" state, which
+// would otherwise flash for the debounce window before body hits arrive.
+const contentSearchPending = ref(false);
+const contentSearchQuery = ref("");
+let contentSearchGeneration = 0;
+let contentSearchTimer: ReturnType<typeof setTimeout> | undefined;
+
+const contentMatchPaths = computed<ReadonlySet<string>>(() => contentMatchPathSet(contentSearchResult.value));
+
+function clearContentSearch() {
+ contentSearchGeneration++;
+ if (contentSearchTimer !== undefined) {
+ clearTimeout(contentSearchTimer);
+ contentSearchTimer = undefined;
+ }
+ contentSearchResult.value = null;
+ contentSearchQuery.value = "";
+ contentSearching.value = false;
+ contentSearchPending.value = false;
+}
+
+/**
+ * Walks the loaded tree once and derives what the content search needs: the
+ * extensions to filter on and how deep the backend walk may go.
+ *
+ * Depth is measured against the tree itself rather than a constant: the tree is
+ * shown from `folders[].entries`, so a hit below its deepest file could never
+ * render. `WalkBuilder` counts the root as depth 0, while a direct child of a
+ * root is tree depth 0 — hence `deepestTreeDepth + 1`. Deriving it from the
+ * data means the panel's depth can never drift from the scanner's own contract
+ * (a duplicated `MAX_SCAN_DEPTH` would).
+ */
+function visibleSqlFileSearchScope(): { extensions: string[]; maxDepth: number } {
+ const extensions = new Set<string>();
+ let deepestFileDepth = -1;
+ const visit = (items: SqlFileEntry[], depth: number) => {
+ for (const item of items) {
+ if (item.is_dir) {
+ visit(item.children, depth + 1);
+ continue;
+ }
+ if (depth > deepestFileDepth) deepestFileDepth = depth;
+ const dot = item.name.lastIndexOf(".");
+ // A dotless name has no extension; only dotted names contribute a filter.
+ if (dot > 0 && dot < item.name.length - 1) extensions.add(item.name.slice(dot + 1).toLowerCase());
+ }
+ };
+ for (const folder of folders.value) visit(folder.entries, 0);
+ // Roots are all walked with a single depth, so use the deepest one. The tree
+ // is already depth-capped by the scanner, which keeps this bounded.
+ return { extensions: [...extensions], maxDepth: Math.max(deepestFileDepth + 1, 1) };
+}
+
+async function runContentSearch(query: string) {
+ if (!query) {
+ clearContentSearch();
+ return;
+ }
+ // Web runtime has no filesystem search (the HTTP stub throws); stay on the
+ // in-memory name filter instead of issuing a request that always fails.
+ if (!isTauriRuntime()) {
+ contentSearchPending.value = false;
+ return;
+ }
+ const roots = folders.value.map((folder) => folder.path);
+ // Nothing to search against (no folders open, or a folder still loading) —
+ // keep the name-only tree and skip a request that would return nothing.
+ if (roots.length === 0) {
+ contentSearchResult.value = null;
+ contentSearchQuery.value = "";
+ contentSearching.value = false;
+ contentSearchPending.value = false;
+ return;
+ }
+ const generation = ++contentSearchGeneration;
+ const { extensions, maxDepth } = visibleSqlFileSearchScope();
+ // Nothing loaded yet (folders still scanning): a search without the panel's
+ // extension set would walk unrelated files, so wait for the next reload.
+ if (extensions.length === 0) {
+ contentSearching.value = false;
+ contentSearchPending.value = false;
+ return;
+ }
+ contentSearching.value = true;
+ try {
+ const result = await searchSqlFileContents({ roots, query, extensions, maxDepth });
+ // Discard the answer if a newer query started meanwhile, or if the box no
+ // longer shows this query — otherwise old hits would widen the tree.
+ if (generation !== contentSearchGeneration || query !== searchQuery.value) return;
+ contentSearchResult.value = result;
+ contentSearchQuery.value = query;
+ } catch {
+ // Web runtime (the stub throws) or a backend walk failure: degrade to name
+ // filtering instead of surfacing an error for every keystroke.
+ if (generation !== contentSearchGeneration) return;
+ contentSearchResult.value = null;
+ contentSearchQuery.value = "";
+ } finally {
+ if (generation === contentSearchGeneration) {
+ contentSearching.value = false;
+ // A newer query may already be queued behind the debounce; keep the
+ // pending flag set for it so the empty state does not flash in between.
+ if (query === searchQuery.value) contentSearchPending.value = false;
+ }
+ }
+}
+
+function scheduleContentSearch(query: string) {
+ if (contentSearchTimer !== undefined) {
+ clearTimeout(contentSearchTimer);
+ contentSearchTimer = undefined;
+ }
+ if (!query) {
+ clearContentSearch();
+ return;
+ }
+ // Outside the desktop runtime there is nothing to wait for: name filtering is
+ // the whole feature there, so the "no results" state must stay immediate.
+ if (!isTauriRuntime()) {
+ contentSearchPending.value = false;
+ return;
+ }
+ contentSearchPending.value = true;
+ contentSearchTimer = setTimeout(() => {
+ contentSearchTimer = undefined;
+ void runContentSearch(query);
+ }, SQL_FILE_CONTENT_SEARCH_DEBOUNCE_MS);
+}
+
+// Results are keyed to the query they were produced for; drop them as soon as
+// the box shows something else so stale hits never widen the tree.
+watch(searchQuery, (query) => {
userCollapsedDuringSearch.value.clear();
+ if (!query) {
+ clearContentSearch();
+ return;
+ }
+ if (contentSearchQuery.value !== query) {
+ contentSearchResult.value = null;
+ contentSearchQuery.value = "";
+ }
+ scheduleContentSearch(query);
});
+// Folder reloads (refresh, add/remove, rename, create/delete) change the file
+// set, so re-run the active search instead of leaving orphan hits behind.
+watch(foldersRevision, () => {
+ const query = searchQuery.value;
+ if (!query) return;
+ scheduleContentSearch(query);
+});
+
+onUnmounted(() => {
+ contentSearchGeneration++;
+ if (contentSearchTimer !== undefined) {
+ clearTimeout(contentSearchTimer);
+ contentSearchTimer = undefined;
+ }
+});
+
+function contentGroupFor(path: string): SqlFileContentMatchGroup | undefined {
+ const normalized = normalizeExternalSqlPath(path);
+ const group = contentSearchResult.value?.matchesByPath.get(normalized);
+ // Guard against a stale result slipping through while a new query is pending.
+ if (!group || contentSearchQuery.value !== searchQuery.value) return undefined;
+ return group;
+}
+
function toggleSortOrder() {
const next = sortOrder.value === "asc" ? "desc" : "asc";
sortOrder.value = next;
@@ -301,6 +478,7 @@ async function loadFolderEntries(folderPath: string): Promise<string | null> {
folders.value[target].loading = false;
folders.value[target].refreshing = false;
}
+ foldersRevision.value++;
}
return null;
}
@@ -360,6 +538,7 @@ async function reloadFolderAfterMutation(folderPath: string) {
async function removeFolder(index: number) {
folders.value.splice(index, 1);
saveFolders();
+ foldersRevision.value++;
}
async function revealInFileManager(path: string) {
@@ -392,7 +571,7 @@ interface ProcessedFolder {
const folderProcessedMap = computed<Map<string, ProcessedFolder>>(() => {
const map = new Map<string, ProcessedFolder>();
for (const folder of folders.value) {
- const res = filterAndSortSqlFileEntries(folder.entries, searchQuery.value, sortOrder.value);
+ const res = filterAndSortSqlFileEntries(folder.entries, searchQuery.value, sortOrder.value, contentMatchPaths.value);
map.set(folder.path, {
entries: res.entries,
autoExpanded: res.autoExpanded,
@@ -489,12 +668,12 @@ function collectDirPaths(entries: SqlFileEntry[], into: Set<string>) {
}
}
-async function openFile(path: string) {
+async function openFile(path: string, reveal?: { line: number; column?: number }) {
if (!isTauriRuntime()) return;
try {
const snapshot = await api.readExternalSqlFileSnapshot(path, externalSqlEditorMaxBytes(settingsStore.editorSettings.externalSqlEditorMaxMb));
const target = resolveExternalSqlFileTargetForActiveTab(path, queryStore.tabs, queryStore.activeTabId, (connectionId) => connectionStore.getConfig(connectionId));
- queryStore.openExternalSqlFile(target.connectionId, target.database, path, snapshot.content, snapshot.version, target.catalog, target.schema, undefined, snapshot.encoding);
+ queryStore.openExternalSqlFile(target.connectionId, target.database, path, snapshot.content, snapshot.version, target.catalog, target.schema, reveal, snapshot.encoding);
} catch (e: any) {
if (isExternalSqlFileTooLargeError(e) && isSqlFilePath(path)) {
executeFile(path);
@@ -505,6 +684,24 @@ async function openFile(path: string) {
}
}
+/** Opens a file at a content-search hit, reusing the normal open flow so
+ * conflict/too-large handling stays identical. */
+async function openContentMatch(path: string, match: SavedSqlLineMatch) {
+ // Mirror the SQL library panel: clicking a snippet makes its file the active
+ // row before opening, so the highlight does not stay on an unrelated entry.
+ const normalizedPath = normalizeExternalSqlPath(path);
+ // Match on the node's own path: `id` is the composite nodeKey, so a path lookup
+ // has to compare against `item.path` (as locateActiveFile does).
+ const index = visibleItems.value.findIndex((item) => item.type === "file" && normalizeExternalSqlPath(item.path) === normalizedPath);
+ if (index >= 0) {
+ const item = visibleItems.value[index];
+ selectedKeys.value = new Set();
+ activeKey.value = item.id;
+ selectionAnchorKey.value = item.id;
+ }
+ await openFile(path, { line: match.lineNumber, column: match.column });
+}
+
// Open the App-level SQL file execution dialog with this file pre-selected so
// the user can review its statements and pick a connection/database before run.
function executeFile(path: string) {
@@ -1090,6 +1287,7 @@ function clearContextTarget() {
<div class="relative">
<Search class="absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-muted-foreground" />
<input data-sql-file-search v-model="searchText" autocapitalize="off" autocorrect="off" spellcheck="false" class="w-full h-6 pl-7 pr-6 text-[13px] rounded border border-border bg-background focus:outline-none focus:ring-1 focus:ring-ring" :placeholder="t('grid.search')" />
+ <Loader2 v-if="contentSearching" data-sql-file-content-searching class="absolute right-6 top-1/2 -translate-y-1/2 h-3 w-3 animate-spin text-muted-foreground" />
<button v-if="searchText" type="button" class="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground" @click="searchText = ''">
<X class="h-3 w-3" />
</button>
@@ -1181,82 +1379,92 @@ function clearContextTarget() {
<div v-else-if="folder.entries.length === 0" class="px-3 py-2 text-xs text-muted-foreground">
{{ t("sqlFileTree.noSqlFiles") }}
</div>
- <div v-else-if="searchQuery && getProcessedEntries(folder.path).length === 0" data-sql-file-empty-search class="px-3 py-2 text-xs text-muted-foreground">
+ <div v-else-if="searchQuery && !contentSearchPending && getProcessedEntries(folder.path).length === 0" data-sql-file-empty-search class="px-3 py-2 text-xs text-muted-foreground">
{{ t("grid.noSearchResults") }}
</div>
<div v-else>
- <div
- data-sql-file-row="true"
- v-for="{ entry, depth } in flatTree(getProcessedEntries(folder.path), getEffectiveExpanded(folder))"
- :key="entry.path"
- :data-sql-file-path="entry.path"
- :aria-current="activeKey === nodeKey(folder.path, entry.is_dir ? 'dir' : 'file', entry.path) ? 'true' : undefined"
- class="flex cursor-default select-none items-center gap-1 px-2 py-1 text-sm"
- :class="[entry.is_dir ? 'rounded-sm' : 'rounded-none', isPathHighlighted(folder.path, entry.is_dir ? 'dir' : 'file', entry.path) ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/40']"
- :style="{ paddingLeft: depth * 16 + 8 + 'px' }"
- role="treeitem"
- :id="visibleRowIds.get(folder)?.get(entry.path)"
- :aria-level="depth + 2"
- :aria-selected="isPathHighlighted(folder.path, entry.is_dir ? 'dir' : 'file', entry.path)"
- :aria-expanded="entry.is_dir ? getEffectiveExpanded(folder).has(entry.path) : undefined"
- @click.stop="handlePathClick(folder.path, entry.path, entry.is_dir ? 'dir' : 'file', $event)"
- @dblclick.stop="handlePathDoubleClick(folder.path, entry.path, entry.is_dir ? 'dir' : 'file', $event)"
- @contextmenu.capture="
- contextTarget = entry.is_dir ? { kind: 'dir', folderPath: folder.path, entry } : { kind: 'file', folderPath: folder.path, entry };
- activeKey = nodeKey(folder.path, entry.is_dir ? 'dir' : 'file', entry.path);
- "
- @contextmenu.prevent="
- contextTarget = entry.is_dir ? { kind: 'dir', folderPath: folder.path, entry } : { kind: 'file', folderPath: folder.path, entry };
- activeKey = nodeKey(folder.path, entry.is_dir ? 'dir' : 'file', entry.path);
- onContextMenu($event);
- "
- >
- <template v-if="entry.is_dir">
- <ChevronRight v-if="!getEffectiveExpanded(folder).has(entry.path)" class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <ChevronDown v-else class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <FolderClosed v-if="!getEffectiveExpanded(folder).has(entry.path)" class="h-4 w-4 shrink-0 text-amber-500" />
- <FolderOpen v-else class="h-4 w-4 shrink-0 text-amber-500" />
- </template>
- <template v-else>
- <span class="w-3.5 shrink-0" />
- <FileCode class="h-4 w-4 shrink-0 text-blue-500" />
- </template>
- <span class="truncate ml-1 flex-1">{{ entry.name }}</span>
- <template v-if="entry.is_dir">
- <LightTooltip :text="t('sqlFileTree.newSqlFile')" side="bottom" :delay="0" :close-delay="0" nowrap>
- <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openCreateDialog(folder.path, entry.path)">
- <FilePlus class="h-3 w-3" />
- </Button>
- </LightTooltip>
- <LightTooltip :text="t('sqlFileTree.newFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
- <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openCreateFolderDialog(folder.path, entry.path)">
- <FolderPlus class="h-3 w-3" />
- </Button>
- </LightTooltip>
- <LightTooltip :text="t('sqlFileTree.renameFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
- <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openRenameFolderDialog({ kind: 'dir', folderPath: folder.path, entry })">
- <Pencil class="h-3 w-3" />
- </Button>
- </LightTooltip>
- <LightTooltip :text="t('sqlFileTree.deleteFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
- <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-destructive" @click.stop="openDeleteFolderDialog({ kind: 'dir', folderPath: folder.path, entry })">
- <Trash2 class="h-3 w-3" />
- </Button>
- </LightTooltip>
- </template>
- <template v-else>
- <LightTooltip :text="t('sqlFileTree.renameFile')" side="bottom" :delay="0" :close-delay="0" nowrap>
- <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openRenameDialog({ kind: 'file', folderPath: folder.path, entry })">
- <Pencil class="h-3 w-3" />
- </Button>
- </LightTooltip>
- <LightTooltip :text="t('sqlFileTree.deleteFile')" side="bottom" :delay="0" :close-delay="0" nowrap>
- <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-destructive" @click.stop="openDeleteDialog({ kind: 'file', folderPath: folder.path, entry })">
- <Trash2 class="h-3 w-3" />
- </Button>
- </LightTooltip>
- </template>
- </div>
+ <template v-for="{ entry, depth } in flatTree(getProcessedEntries(folder.path), getEffectiveExpanded(folder))" :key="entry.path">
+ <div
+ data-sql-file-row="true"
+ :data-sql-file-path="entry.path"
+ :aria-current="activeKey === nodeKey(folder.path, entry.is_dir ? 'dir' : 'file', entry.path) ? 'true' : undefined"
+ class="flex cursor-default select-none items-center gap-1 px-2 py-1 text-sm"
+ :class="[entry.is_dir ? 'rounded-sm' : 'rounded-none', isPathHighlighted(folder.path, entry.is_dir ? 'dir' : 'file', entry.path) ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/40']"
+ :style="{ paddingLeft: depth * 16 + 8 + 'px' }"
+ role="treeitem"
+ :id="visibleRowIds.get(folder)?.get(entry.path)"
+ :aria-level="depth + 2"
+ :aria-selected="isPathHighlighted(folder.path, entry.is_dir ? 'dir' : 'file', entry.path)"
+ :aria-expanded="entry.is_dir ? getEffectiveExpanded(folder).has(entry.path) : undefined"
+ @click.stop="handlePathClick(folder.path, entry.path, entry.is_dir ? 'dir' : 'file', $event)"
+ @dblclick.stop="handlePathDoubleClick(folder.path, entry.path, entry.is_dir ? 'dir' : 'file', $event)"
+ @contextmenu.capture="
+ contextTarget = entry.is_dir ? { kind: 'dir', folderPath: folder.path, entry } : { kind: 'file', folderPath: folder.path, entry };
+ activeKey = nodeKey(folder.path, entry.is_dir ? 'dir' : 'file', entry.path);
+ "
+ @contextmenu.prevent="
+ contextTarget = entry.is_dir ? { kind: 'dir', folderPath: folder.path, entry } : { kind: 'file', folderPath: folder.path, entry };
+ activeKey = nodeKey(folder.path, entry.is_dir ? 'dir' : 'file', entry.path);
+ onContextMenu($event);
+ "
+ >
+ <template v-if="entry.is_dir">
+ <ChevronRight v-if="!getEffectiveExpanded(folder).has(entry.path)" class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <ChevronDown v-else class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <FolderClosed v-if="!getEffectiveExpanded(folder).has(entry.path)" class="h-4 w-4 shrink-0 text-amber-500" />
+ <FolderOpen v-else class="h-4 w-4 shrink-0 text-amber-500" />
+ </template>
+ <template v-else>
+ <span class="w-3.5 shrink-0" />
+ <FileCode class="h-4 w-4 shrink-0 text-blue-500" />
+ </template>
+ <span class="truncate ml-1 flex-1">{{ entry.name }}</span>
+ <template v-if="entry.is_dir">
+ <LightTooltip :text="t('sqlFileTree.newSqlFile')" side="bottom" :delay="0" :close-delay="0" nowrap>
+ <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openCreateDialog(folder.path, entry.path)">
+ <FilePlus class="h-3 w-3" />
+ </Button>
+ </LightTooltip>
+ <LightTooltip :text="t('sqlFileTree.newFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
+ <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openCreateFolderDialog(folder.path, entry.path)">
+ <FolderPlus class="h-3 w-3" />
+ </Button>
+ </LightTooltip>
+ <LightTooltip :text="t('sqlFileTree.renameFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
+ <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openRenameFolderDialog({ kind: 'dir', folderPath: folder.path, entry })">
+ <Pencil class="h-3 w-3" />
+ </Button>
+ </LightTooltip>
+ <LightTooltip :text="t('sqlFileTree.deleteFolder')" side="bottom" :delay="0" :close-delay="0" nowrap>
+ <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-destructive" @click.stop="openDeleteFolderDialog({ kind: 'dir', folderPath: folder.path, entry })">
+ <Trash2 class="h-3 w-3" />
+ </Button>
+ </LightTooltip>
+ </template>
+ <template v-else>
+ <LightTooltip :text="t('sqlFileTree.renameFile')" side="bottom" :delay="0" :close-delay="0" nowrap>
+ <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" @click.stop="openRenameDialog({ kind: 'file', folderPath: folder.path, entry })">
+ <Pencil class="h-3 w-3" />
+ </Button>
+ </LightTooltip>
+ <LightTooltip :text="t('sqlFileTree.deleteFile')" side="bottom" :delay="0" :close-delay="0" nowrap>
+ <Button variant="ghost" size="icon" class="h-4 w-4 shrink-0 text-muted-foreground hover:text-destructive" @click.stop="openDeleteDialog({ kind: 'file', folderPath: folder.path, entry })">
+ <Trash2 class="h-3 w-3" />
+ </Button>
+ </LightTooltip>
+ </template>
+ </div>
+ <!-- Content hits render directly under their file row so the
+ matched lines are visible where the file lives. -->
+ <SqlSearchMatchSnippet
+ v-if="!entry.is_dir && contentGroupFor(entry.path)"
+ :data-sql-file-content-snippet="entry.path"
+ :matches="contentGroupFor(entry.path)?.matches ?? []"
+ :total-matches="contentGroupFor(entry.path)?.totalMatches ?? 0"
+ :depth="depth"
+ @select-match="(match) => openContentMatch(entry.path, match)"
+ />
+ </template>
</div>
</div>
</div>
diff --git a/apps/desktop/src/components/layout/SqlLibrarySearchSnippet.vue b/apps/desktop/src/components/layout/SqlLibrarySearchSnippet.vue
index 2807fae236..a33154e253 100644
--- a/apps/desktop/src/components/layout/SqlLibrarySearchSnippet.vue
+++ b/apps/desktop/src/components/layout/SqlLibrarySearchSnippet.vue
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { computed, ref } from "vue";
-import { useI18n } from "vue-i18n";
import type { SavedSqlFile } from "@/types/database";
-import { findSavedSqlSearchMatches, formatMatchTooltip, type SavedSqlLineMatch } from "@/lib/savedSql/savedSqlSearch";
+import { findSavedSqlSearchMatches, type SavedSqlLineMatch } from "@/lib/savedSql/savedSqlSearch";
+import SqlSearchMatchSnippet from "@/components/layout/SqlSearchMatchSnippet.vue";
const props = withDefaults(
defineProps<{
@@ -19,7 +19,10 @@ const emit = defineEmits<{
selectMatch: [match: SavedSqlLineMatch];
}>();
-const { t } = useI18n();
+/** Collapsed view shows 3; expanding builds at most this many snippets. */
+const COLLAPSED_MATCHES = 3;
+const EXPANDED_MATCHES = 100;
+
const expanded = ref(false);
const searchResult = computed(() => {
@@ -27,45 +30,18 @@ const searchResult = computed(() => {
return { matches: [], totalMatches: 0 };
}
return findSavedSqlSearchMatches(props.file.sql, props.query, {
- maxMatches: expanded.value ? 100 : 3,
+ // Snippet construction is per-line work, so it stays capped until the list
+ // is actually expanded (unchanged behavior from before the shared component).
+ maxMatches: expanded.value ? EXPANDED_MATCHES : COLLAPSED_MATCHES,
});
});
const matches = computed(() => searchResult.value.matches);
const totalMatches = computed(() => searchResult.value.totalMatches);
-const hasHiddenMatches = computed(() => totalMatches.value > 3);
-
-function toggleExpanded() {
- expanded.value = !expanded.value;
-}
-
-function handleSnippetClick(match: SavedSqlLineMatch) {
- emit("selectMatch", match);
-}
</script>
<template>
- <div v-if="matches.length > 0" class="dbx-sql-library-snippets mb-1 mt-0.5 space-y-0.5 select-none" :style="{ paddingLeft: `${24 + depth * 16}px` }" data-no-drag="true" @mousedown.stop>
- <div
- v-for="match in matches"
- :key="match.lineNumber"
- class="group/snippet flex cursor-pointer items-center gap-1.5 rounded py-0.5 pr-2 font-mono text-[11px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground"
- :title="formatMatchTooltip(match)"
- @click.stop="handleSnippetClick(match)"
- >
- <span class="shrink-0 text-[10px] text-muted-foreground/70 select-none"> L{{ match.lineNumber }} </span>
- <span class="min-w-0 flex-1 truncate">
- <template v-for="(seg, idx) in match.segments" :key="idx">
- <mark v-if="seg.matched" class="rounded-[2px] bg-amber-300/80 px-0.5 text-foreground dark:bg-amber-500/40">{{ seg.text }}</mark>
- <span v-else>{{ seg.text }}</span>
- </template>
- </span>
- </div>
-
- <div v-if="hasHiddenMatches" class="pt-0.5 text-[11px]">
- <button type="button" class="text-[11px] font-normal text-primary hover:underline hover:text-primary/80 select-none" @click.stop="toggleExpanded">
- {{ expanded ? t("sqlLibrary.collapseMatches") : t("sqlLibrary.moreMatches", { count: totalMatches - 3 }) }}
- </button>
- </div>
- </div>
+ <!-- The class falls through to the shared component's root, keeping the
+ historical `.dbx-sql-library-snippets` hook (and its spec) working. -->
+ <SqlSearchMatchSnippet class="dbx-sql-library-snippets" :matches="matches" :total-matches="totalMatches" :depth="depth" :initial-visible="COLLAPSED_MATCHES" @expanded-change="(next) => (expanded = next)" @select-match="(match) => emit('selectMatch', match)" />
</template>
diff --git a/apps/desktop/src/components/layout/SqlSearchMatchSnippet.vue b/apps/desktop/src/components/layout/SqlSearchMatchSnippet.vue
new file mode 100644
index 0000000000..d452b9e6db
--- /dev/null
+++ b/apps/desktop/src/components/layout/SqlSearchMatchSnippet.vue
@@ -0,0 +1,71 @@
+<script setup lang="ts">
+import { computed, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import { formatMatchTooltip, type SavedSqlLineMatch } from "@/lib/savedSql/savedSqlSearch";
+
+/**
+ * Presentational snippet list shared by the SQL library panel and the external
+ * SQL file panel: line badge + highlighted segments, `initialVisible` rows by
+ * default, expandable up to the matches the caller supplied.
+ */
+const props = withDefaults(
+ defineProps<{
+ matches: SavedSqlLineMatch[];
+ totalMatches: number;
+ depth?: number;
+ initialVisible?: number;
+ }>(),
+ {
+ depth: 0,
+ initialVisible: 3,
+ },
+);
+
+const emit = defineEmits<{
+ selectMatch: [match: SavedSqlLineMatch];
+ /** Lets a caller that computes matches lazily (e.g. from full file text)
+ * widen its own cap when the list is expanded. */
+ expandedChange: [expanded: boolean];
+}>();
+
+const { t } = useI18n();
+const expanded = ref(false);
+
+const visibleMatches = computed(() => (expanded.value ? props.matches : props.matches.slice(0, props.initialVisible)));
+const hasHiddenMatches = computed(() => props.totalMatches > props.initialVisible);
+
+function toggleExpanded() {
+ expanded.value = !expanded.value;
+ emit("expandedChange", expanded.value);
+}
+
+function handleSnippetClick(match: SavedSqlLineMatch) {
+ emit("selectMatch", match);
+}
+</script>
+
+<template>
+ <div v-if="visibleMatches.length > 0" class="dbx-search-match-snippets mb-1 mt-0.5 space-y-0.5 select-none" :style="{ paddingLeft: `${24 + depth * 16}px` }" data-no-drag="true" @mousedown.stop>
+ <div
+ v-for="match in visibleMatches"
+ :key="match.lineNumber"
+ class="group/snippet flex cursor-pointer items-center gap-1.5 rounded py-0.5 pr-2 font-mono text-[11px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground"
+ :title="formatMatchTooltip(match)"
+ @click.stop="handleSnippetClick(match)"
+ >
+ <span class="shrink-0 text-[10px] text-muted-foreground/70 select-none"> L{{ match.lineNumber }} </span>
+ <span class="min-w-0 flex-1 truncate">
+ <template v-for="(seg, idx) in match.segments" :key="idx">
+ <mark v-if="seg.matched" class="rounded-[2px] bg-amber-300/80 px-0.5 text-foreground dark:bg-amber-500/40">{{ seg.text }}</mark>
+ <span v-else>{{ seg.text }}</span>
+ </template>
+ </span>
+ </div>
+
+ <div v-if="hasHiddenMatches" class="pt-0.5 text-[11px]">
+ <button type="button" class="text-[11px] font-normal text-primary hover:underline hover:text-primary/80 select-none" @click.stop="toggleExpanded">
+ {{ expanded ? t("sqlLibrary.collapseMatches") : t("sqlLibrary.moreMatches", { count: totalMatches - initialVisible }) }}
+ </button>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/layout/__tests__/SqlFilePanel.contentSearch.spec.ts b/apps/desktop/src/components/layout/__tests__/SqlFilePanel.contentSearch.spec.ts
new file mode 100644
index 0000000000..0f548f1939
--- /dev/null
+++ b/apps/desktop/src/components/layout/__tests__/SqlFilePanel.contentSearch.spec.ts
@@ -0,0 +1,234 @@
+// @vitest-environment happy-dom
+
+import { createApp, nextTick, type App } from "vue";
+import { createPinia, setActivePinia } from "pinia";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import type { GlobalSearchMatch } from "@/lib/backend/api";
+import { useQueryStore } from "@/stores/queryStore";
+
+const mocks = vi.hoisted(() => ({
+ isTauri: true,
+ globalSearch: vi.fn(async (_request: unknown): Promise<GlobalSearchMatch[]> => []),
+ readSnapshot: vi.fn(async () => ({ content: "SELECT 1;", version: { mtimeMs: 1, size: 9 } })),
+}));
+
+vi.mock("@/lib/sqlFile/sqlFileFolders", () => ({
+ getSqlFileFilter: () => "*.sql",
+ getSqlFileFolderPaths: () => ["/sql"],
+ saveSqlFileFilter: vi.fn(),
+ saveSqlFileFolderPaths: vi.fn(),
+ notifySqlFileFoldersChanged: vi.fn(),
+}));
+
+vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => mocks.isTauri }));
+
+const testEntries = [
+ {
+ name: "queries",
+ path: "/sql/queries",
+ is_dir: true,
+ children: [
+ { name: "01_find_user.sql", path: "/sql/queries/01_find_user.sql", is_dir: false, children: [] },
+ { name: "02_orders.sql", path: "/sql/queries/02_orders.sql", is_dir: false, children: [] },
+ ],
+ },
+ {
+ name: "migrations",
+ path: "/sql/migrations",
+ is_dir: true,
+ children: [{ name: "01_init.sql", path: "/sql/migrations/01_init.sql", is_dir: false, children: [] }],
+ },
+ { name: "zebra.sql", path: "/sql/zebra.sql", is_dir: false, children: [] },
+ { name: "alpha.sql", path: "/sql/alpha.sql", is_dir: false, children: [] },
+];
+
+vi.mock("@/lib/backend/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/backend/api")>()),
+ listSqlFilesInFolder: vi.fn(async () => JSON.parse(JSON.stringify(testEntries))),
+ readExternalSqlFileSnapshot: mocks.readSnapshot,
+ globalSearch: mocks.globalSearch,
+}));
+
+import SqlFilePanel from "../SqlFilePanel.vue";
+
+const mounted: Array<{ app: App; host: HTMLElement }> = [];
+
+async function mountPanel() {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ const queryStore = useQueryStore();
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(SqlFilePanel);
+ app.use(pinia);
+ app.use(i18n);
+ app.mount(host);
+ mounted.push({ app, host });
+ await vi.waitFor(() => expect(host.textContent).toContain("alpha.sql"));
+ return { host, queryStore };
+}
+
+function typeQuery(host: HTMLElement, value: string) {
+ const input = host.querySelector<HTMLInputElement>("input[data-sql-file-search]")!;
+ input.value = value;
+ input.dispatchEvent(new Event("input"));
+}
+
+function hit(overrides: Partial<GlobalSearchMatch> & { path: string; line: number; column: number }): GlobalSearchMatch {
+ return {
+ fileName: overrides.path.split("/").pop() ?? overrides.path,
+ matchText: "needle",
+ lineText: "SELECT needle FROM t",
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ mocks.isTauri = true;
+ mocks.globalSearch.mockReset();
+ mocks.globalSearch.mockResolvedValue([]);
+ mocks.readSnapshot.mockClear();
+});
+
+afterEach(() => {
+ for (const { app, host } of mounted.splice(0)) {
+ app.unmount();
+ host.remove();
+ }
+ vi.restoreAllMocks();
+});
+
+describe("SqlFilePanel content search", () => {
+ it("shows content-only matches with their snippet and auto-expands the parent folder", async () => {
+ const { host } = await mountPanel();
+ mocks.globalSearch.mockResolvedValue([hit({ path: "/sql/queries/02_orders.sql", line: 3, column: 8 })]);
+
+ typeQuery(host, "needle");
+ await vi.waitFor(() => expect(host.querySelector('[data-sql-file-path="/sql/queries/02_orders.sql"]')).not.toBeNull());
+
+ // The folder name does not match "needle" but must be visible and expanded.
+ expect(host.querySelector('[data-sql-file-path="/sql/queries"]')).not.toBeNull();
+ expect(host.querySelector('[data-sql-file-path="/sql/alpha.sql"]')).toBeNull();
+
+ const snippet = host.querySelector<HTMLElement>('[data-sql-file-content-snippet="/sql/queries/02_orders.sql"]');
+ expect(snippet).not.toBeNull();
+ expect(snippet!.textContent).toContain("L3");
+ expect(snippet!.querySelector("mark")?.textContent).toBe("needle");
+
+ // Content results must not be mistaken for "no results".
+ expect(host.querySelector("[data-sql-file-empty-search]")).toBeNull();
+
+ // The backend is asked for the panel's file set, ignore rules disabled, and
+ // only as deep as the tree itself: fixture files sit at tree depth 1
+ // (queries/01_find_user.sql, alpha.sql…), i.e. WalkBuilder depth 2.
+ expect(mocks.globalSearch).toHaveBeenCalledWith(expect.objectContaining({ roots: ["/sql"], query: "needle", extensions: ["sql"], respectIgnoreRules: false, maxDepth: 2 }));
+ });
+
+ it("opens the file at the hit line and column when a snippet is clicked", async () => {
+ const { host, queryStore } = await mountPanel();
+ mocks.globalSearch.mockResolvedValue([hit({ path: "/sql/queries/02_orders.sql", line: 3, column: 8 })]);
+ const openExternalSqlFile = vi.spyOn(queryStore, "openExternalSqlFile");
+
+ typeQuery(host, "needle");
+ const snippetRow = await vi.waitFor(() => {
+ const row = host.querySelector<HTMLElement>('[data-sql-file-content-snippet="/sql/queries/02_orders.sql"] .group\\/snippet');
+ expect(row).not.toBeNull();
+ return row!;
+ });
+
+ snippetRow.click();
+ await vi.waitFor(() => expect(openExternalSqlFile).toHaveBeenCalledTimes(1));
+
+ const args = openExternalSqlFile.mock.calls[0];
+ expect(args[2]).toBe("/sql/queries/02_orders.sql");
+ expect(args[7]).toEqual({ line: 3, column: 8 });
+
+ // The clicked file becomes the active row, like the SQL library panel.
+ await vi.waitFor(() => expect(host.querySelector('[data-sql-file-path="/sql/queries/02_orders.sql"]')!.getAttribute("aria-current")).toBe("true"));
+ });
+
+ it("shows truncated snippets and expands to the full match list", async () => {
+ const { host } = await mountPanel();
+ mocks.globalSearch.mockResolvedValue([1, 2, 3, 4, 5].map((line) => hit({ path: "/sql/queries/02_orders.sql", line, column: 1 })));
+
+ typeQuery(host, "needle");
+ const snippet = await vi.waitFor(() => {
+ const element = host.querySelector<HTMLElement>('[data-sql-file-content-snippet="/sql/queries/02_orders.sql"]');
+ expect(element).not.toBeNull();
+ return element!;
+ });
+
+ expect(snippet.querySelectorAll(".group\\/snippet")).toHaveLength(3);
+ const moreButton = [...snippet.querySelectorAll("button")].find((button) => button.textContent?.includes("2"));
+ expect(moreButton).toBeDefined();
+ moreButton!.click();
+ await nextTick();
+ expect(snippet.querySelectorAll(".group\\/snippet")).toHaveLength(5);
+ });
+
+ it("debounces lookups so fast typing issues a single final request", async () => {
+ const { host } = await mountPanel();
+ typeQuery(host, "n");
+ typeQuery(host, "ne");
+ typeQuery(host, "needle");
+
+ expect(mocks.globalSearch).not.toHaveBeenCalled();
+ await vi.waitFor(() => expect(mocks.globalSearch).toHaveBeenCalledTimes(1));
+ expect(mocks.globalSearch).toHaveBeenCalledWith(expect.objectContaining({ query: "needle" }));
+ });
+
+ it("discards results from a superseded query", async () => {
+ const { host } = await mountPanel();
+ let resolveFirst: ((matches: GlobalSearchMatch[]) => void) | undefined;
+ mocks.globalSearch.mockImplementationOnce(
+ () =>
+ new Promise<GlobalSearchMatch[]>((resolve) => {
+ resolveFirst = resolve;
+ }),
+ );
+ mocks.globalSearch.mockResolvedValueOnce([hit({ path: "/sql/migrations/01_init.sql", line: 2, column: 1 })]);
+
+ typeQuery(host, "needle");
+ await vi.waitFor(() => expect(mocks.globalSearch).toHaveBeenCalledTimes(1));
+
+ // Second query starts (and finishes) before the first response arrives.
+ typeQuery(host, "other");
+ await vi.waitFor(() => expect(host.querySelector('[data-sql-file-path="/sql/migrations/01_init.sql"]')).not.toBeNull());
+
+ resolveFirst!([hit({ path: "/sql/queries/02_orders.sql", line: 1, column: 1 })]);
+ await nextTick();
+ await nextTick();
+
+ // The late answer for "needle" must not widen the tree for "other".
+ expect(host.querySelector('[data-sql-file-path="/sql/queries/02_orders.sql"]')).toBeNull();
+ });
+
+ it("restores the full tree when the query is cleared", async () => {
+ const { host } = await mountPanel();
+ mocks.globalSearch.mockResolvedValue([hit({ path: "/sql/queries/02_orders.sql", line: 1, column: 1 })]);
+
+ typeQuery(host, "needle");
+ await vi.waitFor(() => expect(host.querySelector("[data-sql-file-content-snippet]")).not.toBeNull());
+
+ host.querySelector<HTMLButtonElement>("button.absolute.right-1\\.5")!.click();
+ await nextTick();
+
+ const restored = Array.from(host.querySelectorAll<HTMLElement>("[data-sql-file-path]")).map((row) => row.querySelector(".truncate")?.textContent?.trim());
+ expect(restored).toEqual(["migrations", "queries", "alpha.sql", "zebra.sql"]);
+ expect(host.querySelector("[data-sql-file-content-snippet]")).toBeNull();
+ });
+
+ it("degrades to name-only filtering outside the desktop runtime", async () => {
+ mocks.isTauri = false;
+ const { host } = await mountPanel();
+
+ typeQuery(host, "orders");
+ await nextTick();
+ await nextTick();
+
+ // Name matching still works instantly, and no backend search is attempted.
+ expect(host.querySelector('[data-sql-file-path="/sql/queries/02_orders.sql"]')).not.toBeNull();
+ expect(mocks.globalSearch).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 191e651f94..39cb6451d6 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -3083,6 +3083,9 @@ export interface GlobalSearchRequest {
useRegex?: boolean;
wholeWord?: boolean;
limit?: number;
+ respectIgnoreRules?: boolean;
+ /** Max traversal depth (`WalkBuilder` semantics: root = 0, its entries = 1). */
+ maxDepth?: number;
}
export interface GlobalSearchMatch {
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index c0c1798fe0..383be89f85 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -1407,6 +1407,18 @@ export interface GlobalSearchRequest {
useRegex?: boolean;
wholeWord?: boolean;
limit?: number;
+ /**
+ * Whether the backend walker skips hidden paths and honors ignore files.
+ * Omit (or `true`) for the default Quick Open behavior; pass `false` to search
+ * exactly the files a raw directory listing shows (SQL file panel).
+ */
+ respectIgnoreRules?: boolean;
+ /**
+ * Maximum traversal depth using `WalkBuilder` semantics: the root itself is
+ * depth 0 and its direct entries are depth 1. Omit for an unbounded walk
+ * (Quick Open behavior).
+ */
+ maxDepth?: number;
}
export interface GlobalSearchMatch {
diff --git a/apps/desktop/src/lib/sql/__tests__/sqlFileContentSearch.spec.ts b/apps/desktop/src/lib/sql/__tests__/sqlFileContentSearch.spec.ts
new file mode 100644
index 0000000000..fbc3e2ffbf
--- /dev/null
+++ b/apps/desktop/src/lib/sql/__tests__/sqlFileContentSearch.spec.ts
@@ -0,0 +1,127 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { GlobalSearchMatch } from "@/lib/backend/api";
+
+const mocks = vi.hoisted(() => ({
+ globalSearch: vi.fn(async (_request: { roots: string[]; query: string; extensions?: string[]; limit?: number; respectIgnoreRules?: boolean; maxDepth?: number }): Promise<GlobalSearchMatch[]> => []),
+}));
+
+vi.mock("@/lib/backend/api", () => ({
+ globalSearch: mocks.globalSearch,
+}));
+
+import { contentMatchPathSet, searchSqlFileContents, SQL_FILE_CONTENT_SEARCH_RESULT_LIMIT, SQL_FILE_SNIPPET_MAX_MATCHES } from "../sqlFileContentSearch";
+
+function hit(overrides: Partial<GlobalSearchMatch> & { path: string; line: number; column: number }): GlobalSearchMatch {
+ const fileName = overrides.path.split("/").pop() ?? overrides.path;
+ return {
+ fileName,
+ matchText: "users",
+ lineText: "SELECT * FROM users",
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ mocks.globalSearch.mockReset();
+ mocks.globalSearch.mockResolvedValue([]);
+});
+
+describe("searchSqlFileContents", () => {
+ it("asks the backend for the panel's file set (ignore rules disabled) and forwards extensions/limit", async () => {
+ await searchSqlFileContents({ roots: ["/sql", "/more"], query: " users ", extensions: ["sql", "ddl"] });
+
+ expect(mocks.globalSearch).toHaveBeenCalledWith({
+ roots: ["/sql", "/more"],
+ query: "users",
+ extensions: ["sql", "ddl"],
+ limit: SQL_FILE_CONTENT_SEARCH_RESULT_LIMIT,
+ respectIgnoreRules: false,
+ maxDepth: undefined,
+ });
+ });
+
+ it("forwards maxDepth so the walk cannot go deeper than the caller's tree", async () => {
+ await searchSqlFileContents({ roots: ["/sql"], query: "users", extensions: ["sql"], maxDepth: 3 });
+
+ expect(mocks.globalSearch).toHaveBeenCalledWith(expect.objectContaining({ maxDepth: 3 }));
+ });
+
+ it("skips the request for an empty query or when no roots are configured", async () => {
+ expect((await searchSqlFileContents({ roots: ["/sql"], query: " " })).matchesByPath.size).toBe(0);
+ expect((await searchSqlFileContents({ roots: [], query: "users" })).matchesByPath.size).toBe(0);
+ expect(mocks.globalSearch).not.toHaveBeenCalled();
+ });
+
+ it("groups hits per file, normalizes paths and ignores filename-match sentinels", async () => {
+ mocks.globalSearch.mockResolvedValue([
+ hit({ path: "C:\\sql\\a.sql", line: 3, column: 15 }),
+ hit({ path: "C:/sql/a.sql", line: 1, column: 10 }),
+ // line 0 is the backend's filename-match sentinel, not a content hit.
+ hit({ path: "C:/sql/b.sql", line: 0, column: 1 }),
+ hit({ path: "C:/sql/b.sql", line: 7, column: 2 }),
+ ]);
+
+ const result = await searchSqlFileContents({ roots: ["/sql"], query: "users" });
+
+ expect([...result.matchesByPath.keys()]).toEqual(["C:/sql/a.sql", "C:/sql/b.sql"]);
+ const a = result.matchesByPath.get("C:/sql/a.sql")!;
+ expect(a.matches.map((match) => match.lineNumber)).toEqual([1, 3]);
+ expect(a.totalMatches).toBe(2);
+ const b = result.matchesByPath.get("C:/sql/b.sql")!;
+ expect(b.matches.map((match) => match.lineNumber)).toEqual([7]);
+ expect(b.totalMatches).toBe(1);
+ });
+
+ it("collapses multiple hits on the same line into one snippet at the first column", async () => {
+ mocks.globalSearch.mockResolvedValue([hit({ path: "/sql/a.sql", line: 2, column: 18 }), hit({ path: "/sql/a.sql", line: 2, column: 4 })]);
+
+ const result = await searchSqlFileContents({ roots: ["/sql"], query: "users" });
+ const group = result.matchesByPath.get("/sql/a.sql")!;
+
+ expect(group.matches).toHaveLength(1);
+ expect(group.matches[0].column).toBe(4);
+ // A same-line repeat is not an extra snippet the user could expand to.
+ expect(group.totalMatches).toBe(1);
+ });
+
+ it("truncates long lines and highlights the match segments", async () => {
+ const longPrefix = "x".repeat(200);
+ mocks.globalSearch.mockResolvedValue([hit({ path: "/sql/a.sql", line: 1, column: longPrefix.length + 1, lineText: `${longPrefix} users trailing` })]);
+
+ const result = await searchSqlFileContents({ roots: ["/sql"], query: "users" });
+ const match = result.matchesByPath.get("/sql/a.sql")!.matches[0];
+
+ expect(match.lineText.startsWith("...")).toBe(true);
+ expect(match.lineText.length).toBeLessThan(210);
+ expect(match.segments.filter((segment) => segment.matched).map((segment) => segment.text)).toEqual(["users"]);
+ });
+
+ it("caps snippets per file but keeps counting the total hits", async () => {
+ mocks.globalSearch.mockResolvedValue([hit({ path: "/sql/a.sql", line: 1, column: 1 }), hit({ path: "/sql/a.sql", line: 2, column: 1 }), hit({ path: "/sql/a.sql", line: 3, column: 1 })]);
+
+ const result = await searchSqlFileContents({ roots: ["/sql"], query: "users", limit: 2 });
+ const group = result.matchesByPath.get("/sql/a.sql")!;
+
+ expect(group.matches).toHaveLength(2);
+ expect(group.totalMatches).toBe(3);
+ });
+
+ it("caps snippets at SQL_FILE_SNIPPET_MAX_MATCHES per file while counting every hit line", async () => {
+ mocks.globalSearch.mockResolvedValue(Array.from({ length: 150 }, (_, index) => hit({ path: "/sql/a.sql", line: index + 1, column: 1 })));
+
+ const result = await searchSqlFileContents({ roots: ["/sql"], query: "users" });
+ const group = result.matchesByPath.get("/sql/a.sql")!;
+
+ expect(group.matches).toHaveLength(SQL_FILE_SNIPPET_MAX_MATCHES);
+ expect(group.totalMatches).toBe(150);
+ expect(mocks.globalSearch).toHaveBeenCalledWith(expect.objectContaining({ limit: SQL_FILE_CONTENT_SEARCH_RESULT_LIMIT }));
+ });
+
+ it("exposes the matched path set for the tree filter", async () => {
+ mocks.globalSearch.mockResolvedValue([hit({ path: "C:\\sql\\a.sql", line: 1, column: 1 })]);
+ const result = await searchSqlFileContents({ roots: ["C:\\sql"], query: "users" });
+
+ expect(contentMatchPathSet(result)).toEqual(new Set(["C:/sql/a.sql"]));
+ expect(contentMatchPathSet(null).size).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/lib/sql/__tests__/sqlFileTreeFilter.spec.ts b/apps/desktop/src/lib/sql/__tests__/sqlFileTreeFilter.spec.ts
index fb5d64f13e..6f95c4a767 100644
--- a/apps/desktop/src/lib/sql/__tests__/sqlFileTreeFilter.spec.ts
+++ b/apps/desktop/src/lib/sql/__tests__/sqlFileTreeFilter.spec.ts
@@ -130,5 +130,48 @@ describe("sqlFileTreeFilter", () => {
expect(result.autoExpanded.size).toBe(0);
expect(result.matchCount).toBe(0);
});
+
+ it("keeps content-matching files whose names do not match and auto-expands their parents", () => {
+ // "needle" matches no file or folder name in the fixture.
+ const result = filterAndSortSqlFileEntries(sampleEntries, "needle", "asc", new Set(["/sql/queries/get_orders.sql", "/sql/migrations/2024/01_init.sql"]));
+
+ expect(result.entries.map((e) => e.name)).toEqual(["migrations", "queries"]);
+ const migrations = result.entries.find((e) => e.name === "migrations")!;
+ expect(migrations.children.map((c) => c.name)).toEqual(["2024"]);
+ expect(migrations.children[0].children.map((c) => c.name)).toEqual(["01_init.sql"]);
+ const queries = result.entries.find((e) => e.name === "queries")!;
+ expect(queries.children.map((c) => c.name)).toEqual(["get_orders.sql"]);
+
+ expect(Array.from(result.autoExpanded).sort()).toEqual(["/sql/migrations", "/sql/migrations/2024", "/sql/queries"]);
+ // matchCount drives folder visibility in the panel, so content-only hits must count.
+ expect(result.matchCount).toBeGreaterThan(0);
+ });
+
+ it("normalizes entry paths before comparing them with the content-match set", () => {
+ // Scanned entries keep native separators on Windows while content-search
+ // paths are normalized, so the comparison has to normalize the entry side.
+ const windowsEntries: SqlFileEntry[] = [{ name: "queries", path: "C:\\sql\\queries", is_dir: true, children: [{ name: "get_orders.sql", path: "C:\\sql\\queries\\get_orders.sql", is_dir: false, children: [] }] }];
+ const result = filterAndSortSqlFileEntries(windowsEntries, "needle", "asc", new Set(["C:/sql/queries/get_orders.sql"]));
+
+ const queries = result.entries.find((e) => e.name === "queries");
+ expect(queries?.children.map((c) => c.name)).toEqual(["get_orders.sql"]);
+ expect(result.autoExpanded.has("C:\\sql\\queries")).toBe(true);
+ });
+
+ it("merges name matches with content matches", () => {
+ const result = filterAndSortSqlFileEntries(sampleEntries, "user", "asc", new Set(["/sql/queries/get_orders.sql"]));
+
+ const queries = result.entries.find((e) => e.name === "queries")!;
+ expect(queries.children.map((c) => c.name)).toEqual(["get_orders.sql", "select_user.sql"]);
+ expect(result.entries.map((e) => e.name)).toEqual(["migrations", "queries"]);
+ });
+
+ it("ignores an empty content-match set", () => {
+ const withEmpty = filterAndSortSqlFileEntries(sampleEntries, "user", "asc", new Set());
+ const withoutSet = filterAndSortSqlFileEntries(sampleEntries, "user", "asc");
+
+ expect(withEmpty.entries).toEqual(withoutSet.entries);
+ expect(withEmpty.matchCount).toBe(withoutSet.matchCount);
+ });
});
});
diff --git a/apps/desktop/src/lib/sql/sqlFileContentSearch.ts b/apps/desktop/src/lib/sql/sqlFileContentSearch.ts
new file mode 100644
index 0000000000..56228e2c3c
--- /dev/null
+++ b/apps/desktop/src/lib/sql/sqlFileContentSearch.ts
@@ -0,0 +1,131 @@
+import * as api from "@/lib/backend/api";
+import type { GlobalSearchMatch } from "@/lib/backend/api";
+import { formatSnippetLine, splitSearchMatchSegments, type SavedSqlLineMatch } from "@/lib/savedSql/savedSqlSearch";
+import { normalizeExternalSqlPath } from "@/lib/sql/sqlFileOpen";
+
+/** Matches the Quick Open content-mode debounce so typing feels the same in both surfaces. */
+export const SQL_FILE_CONTENT_SEARCH_DEBOUNCE_MS = 250;
+/** Upper bound on backend hits; keeps a broad query from returning megabytes of snippets. */
+export const SQL_FILE_CONTENT_SEARCH_RESULT_LIMIT = 500;
+/**
+ * Upper bound on snippets kept per file. Mirrors the SQL library's expanded cap
+ * (`EXPANDED_MATCHES` in SqlLibrarySearchSnippet.vue) so both lists scroll the
+ * same amount; `totalMatches` still reports every distinct matching line, so the
+ * "+N more" label stays honest.
+ */
+export const SQL_FILE_SNIPPET_MAX_MATCHES = 100;
+/** Long lines are truncated around the first match, same as the SQL library list. */
+const SNIPPET_MAX_LINE_LENGTH = 100;
+
+export interface SqlFileContentMatchGroup {
+ path: string;
+ matches: SavedSqlLineMatch[];
+ /** Total hit lines for this file. A line that matches several times counts once. */
+ totalMatches: number;
+}
+
+export interface SqlFileContentSearchResult {
+ matchesByPath: Map<string, SqlFileContentMatchGroup>;
+}
+
+export interface SearchSqlFileContentsOptions {
+ roots: string[];
+ query: string;
+ /** Extensions without the leading dot, e.g. `["sql", "ddl"]`. */
+ extensions?: string[];
+ limit?: number;
+ /**
+ * Max traversal depth in `WalkBuilder` terms (root = 0, its entries = 1).
+ * Callers that render results from a bounded tree pass the tree's own depth so
+ * the walk cannot produce hits they are unable to display.
+ */
+ maxDepth?: number;
+}
+
+interface MutableGroup {
+ path: string;
+ matches: SavedSqlLineMatch[];
+ /** One snippet per line, keyed by line number. */
+ byLine: Map<number, SavedSqlLineMatch>;
+ totalMatches: number;
+}
+
+/**
+ * Turns raw backend hits into per-file snippet groups for the SQL file tree.
+ *
+ * A file can produce several hits for the same line (the backend reports every
+ * occurrence), but the tree shows one snippet per line — the leftmost one,
+ * because that is the occurrence the snippet text is built around. The backend
+ * normally reports hits in reading order; comparing columns keeps this
+ * deterministic instead of relying on that.
+ * `line === 0` is the backend's filename-match sentinel; the tree already
+ * matches on names locally, so those hits are not content.
+ */
+function groupMatches(matches: GlobalSearchMatch[], query: string, limit: number): SqlFileContentSearchResult {
+ const trimmedQuery = query.trim();
+ const matchesByPath = new Map<string, SqlFileContentMatchGroup>();
+ if (!trimmedQuery) return { matchesByPath };
+
+ const groups = new Map<string, MutableGroup>();
+ for (const match of matches) {
+ if (match.line <= 0) continue;
+ const path = normalizeExternalSqlPath(match.path);
+ if (!path) continue;
+ let group = groups.get(path);
+ if (!group) {
+ group = { path, matches: [], byLine: new Map<number, SavedSqlLineMatch>(), totalMatches: 0 };
+ groups.set(path, group);
+ }
+ const existing = group.byLine.get(match.line);
+ if (existing && existing.column <= match.column) continue;
+ const lineText = formatSnippetLine(match.lineText, trimmedQuery, SNIPPET_MAX_LINE_LENGTH);
+ const snippet: SavedSqlLineMatch = {
+ lineNumber: match.line,
+ column: match.column,
+ lineText,
+ segments: splitSearchMatchSegments(lineText, trimmedQuery),
+ };
+ if (!existing) group.totalMatches++;
+ group.byLine.set(match.line, snippet);
+ }
+
+ // One file can hit the global backend limit on its own, so the per-file
+ // snippet list is capped separately; `totalMatches` keeps the full count.
+ const snippetLimit = Math.min(limit, SQL_FILE_SNIPPET_MAX_MATCHES);
+ for (const group of groups.values()) {
+ group.matches = [...group.byLine.values()].sort((a, b) => a.lineNumber - b.lineNumber).slice(0, snippetLimit);
+ matchesByPath.set(group.path, { path: group.path, matches: group.matches, totalMatches: group.totalMatches });
+ }
+ return { matchesByPath };
+}
+
+/**
+ * Searches the given roots for `query` and groups the hits by file path.
+ *
+ * `respectIgnoreRules: false` makes the backend walk the same file set the SQL
+ * file tree lists (raw `read_dir`: hidden files and `.gitignore`d files
+ * included). Results are never cached here — the caller owns debouncing and
+ * discarding stale generations.
+ */
+export async function searchSqlFileContents(options: SearchSqlFileContentsOptions): Promise<SqlFileContentSearchResult> {
+ const query = options.query.trim();
+ const roots = options.roots.filter((root) => root.trim().length > 0);
+ if (!query || roots.length === 0) return { matchesByPath: new Map() };
+
+ const limit = options.limit ?? SQL_FILE_CONTENT_SEARCH_RESULT_LIMIT;
+ const extensions = options.extensions && options.extensions.length > 0 ? options.extensions : undefined;
+ const matches = await api.globalSearch({
+ roots,
+ query,
+ extensions,
+ limit,
+ respectIgnoreRules: false,
+ maxDepth: options.maxDepth,
+ });
+ return groupMatches(matches, query, limit);
+}
+
+/** Normalized paths of every file with at least one content hit. */
+export function contentMatchPathSet(result: SqlFileContentSearchResult | null | undefined): ReadonlySet<string> {
+ return new Set(result?.matchesByPath.keys() ?? []);
+}
diff --git a/apps/desktop/src/lib/sql/sqlFileTreeFilter.ts b/apps/desktop/src/lib/sql/sqlFileTreeFilter.ts
index fb96d4c0ca..4fc96164a4 100644
--- a/apps/desktop/src/lib/sql/sqlFileTreeFilter.ts
+++ b/apps/desktop/src/lib/sql/sqlFileTreeFilter.ts
@@ -1,5 +1,6 @@
import type { SqlFileEntry } from "@/lib/backend/api";
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
+import { normalizeExternalSqlPath } from "@/lib/sql/sqlFileOpen";
const SORT_ORDER_STORAGE_KEY = "dbx-sql-file-sort-order";
export type SqlFileSortOrder = "asc" | "desc";
@@ -76,8 +77,12 @@ function collectMatchingDescendantDirPaths(items: SqlFileEntry[], q: string, aut
* - If a directory's name does not match, but some descendants do, the directory is kept with only the matching descendants,
* and its path is added to `autoExpanded`.
* - If a file matches the query, it is kept.
+ * - A file whose normalized path is in `contentMatchPaths` (i.e. its body matched
+ * the query in the backend content search) is treated as a match too. That keeps
+ * the tree consistent with the snippets rendered under the file row, and makes
+ * ancestor directories auto-expand so the hit is actually visible.
*/
-export function filterAndSortSqlFileEntries(entries: SqlFileEntry[], query: string, order: SqlFileSortOrder = "asc"): SqlFileFilterResult {
+export function filterAndSortSqlFileEntries(entries: SqlFileEntry[], query: string, order: SqlFileSortOrder = "asc", contentMatchPaths?: ReadonlySet<string>): SqlFileFilterResult {
const trimmed = query.trim();
if (!trimmed) {
const sorted = recursivelySortSqlFileEntries(entries, order);
@@ -100,12 +105,18 @@ export function filterAndSortSqlFileEntries(entries: SqlFileEntry[], query: stri
const autoExpanded = new Set<string>();
let matchCount = 0;
+ function fileMatches(item: SqlFileEntry): boolean {
+ if (item.name.toLowerCase().includes(q)) return true;
+ if (!contentMatchPaths || contentMatchPaths.size === 0) return false;
+ return contentMatchPaths.has(normalizeExternalSqlPath(item.path));
+ }
+
function filterEntries(items: SqlFileEntry[]): SqlFileEntry[] {
const result: SqlFileEntry[] = [];
for (const item of items) {
if (!item.is_dir) {
- if (item.name.toLowerCase().includes(q)) {
+ if (fileMatches(item)) {
matchCount++;
result.push(item);
}
diff --git a/src-tauri/src/commands/global_search.rs b/src-tauri/src/commands/global_search.rs
index 83854686b9..3707f8981f 100644
--- a/src-tauri/src/commands/global_search.rs
+++ b/src-tauri/src/commands/global_search.rs
@@ -50,6 +50,20 @@ pub struct GlobalSearchRequest {
pub whole_word: Option<bool>,
#[serde(default)]
pub limit: Option<usize>,
+ /// Whether the walker skips hidden paths and honors ignore files
+ /// (`.gitignore`, `.ignore`, git global/exclude). Defaults to `true`, which
+ /// is the Quick Open behavior. The SQL file panel passes `false` so content
+ /// results cover exactly the files its tree lists (raw `read_dir`, which
+ /// does not filter hidden or ignored files).
+ #[serde(default)]
+ pub respect_ignore_rules: Option<bool>,
+ /// Maximum traversal depth, using `WalkBuilder` semantics: the root itself
+ /// is depth 0, entries directly inside it are depth 1. `None` (the default)
+ /// leaves the walk unbounded, which is the Quick Open behavior. The SQL file
+ /// panel derives this from its loaded tree so the walk can never descend
+ /// deeper than the panel is able to display.
+ #[serde(default)]
+ pub max_depth: Option<usize>,
}
#[derive(Debug, Serialize, Clone)]
@@ -155,7 +169,24 @@ fn search_root(request: &GlobalSearchRequest, root: &str) -> Vec<GlobalSearchMat
let mut results = Vec::new();
let mut builder = WalkBuilder::new(root);
- builder.hidden(true).git_ignore(true).git_global(true).git_exclude(true).follow_links(false);
+ // `WalkBuilder`'s ignore options all default to `true`; flipping them off is
+ // what makes the walk enumerate the same set of files that a plain
+ // `read_dir` scan (used by the SQL file tree) would see.
+ let respect_ignore_rules = request.respect_ignore_rules.unwrap_or(true);
+ builder
+ .hidden(respect_ignore_rules)
+ .ignore(respect_ignore_rules)
+ // `parents` reads ignore files from ancestor directories; leaving it on
+ // would keep honoring rules the caller asked to ignore (and do pointless
+ // parent traversal), so it follows the same flag.
+ .parents(respect_ignore_rules)
+ .git_ignore(respect_ignore_rules)
+ .git_global(respect_ignore_rules)
+ .git_exclude(respect_ignore_rules)
+ .follow_links(false);
+ // Depth 0 is the root itself, so callers measure "levels below the root".
+ // `None` keeps the historical unbounded walk (Quick Open).
+ builder.max_depth(request.max_depth);
builder.filter_entry(|entry| {
if entry.depth() == 0 {
return true;
@@ -271,6 +302,8 @@ mod tests {
use_regex: None,
whole_word: None,
limit: None,
+ respect_ignore_rules: None,
+ max_depth: None,
}
}
@@ -377,4 +410,89 @@ mod tests {
assert!(results[0].path.ends_with("main.sql"));
std::fs::remove_dir_all(&root).unwrap();
}
+
+ /// Creates a root containing a visible file, a hidden directory with a
+ /// file, and a `.gitignore`d file. `.git` is materialized because the
+ /// walker requires a repository for `.gitignore` rules to apply.
+ fn ignore_rules_fixture(label: &str) -> PathBuf {
+ let root = temp_dir(label);
+ std::fs::create_dir_all(root.join(".git")).unwrap();
+ std::fs::write(root.join(".gitignore"), "ignored.sql\n").unwrap();
+ std::fs::write(root.join("visible.sql"), "SELECT needle;\n").unwrap();
+ std::fs::write(root.join("ignored.sql"), "SELECT needle;\n").unwrap();
+ std::fs::create_dir_all(root.join(".hidden")).unwrap();
+ std::fs::write(root.join(".hidden").join("nested.sql"), "SELECT needle;\n").unwrap();
+ root
+ }
+
+ fn matched_file_names(results: &[GlobalSearchMatch]) -> Vec<String> {
+ let mut names: Vec<String> = results.iter().map(|m| m.file_name.clone()).collect();
+ names.sort();
+ names
+ }
+
+ #[tokio::test]
+ async fn default_respects_hidden_and_gitignore_rules() {
+ let root = ignore_rules_fixture("ignore-default");
+ let r = req(&[root.to_str().unwrap()], "needle");
+ assert_eq!(r.respect_ignore_rules, None);
+ let results = global_search(r).await.unwrap();
+ assert_eq!(matched_file_names(&results), vec!["visible.sql".to_string()]);
+ std::fs::remove_dir_all(&root).unwrap();
+ }
+
+ #[tokio::test]
+ async fn respect_ignore_rules_false_walks_hidden_and_ignored_files() {
+ let root = ignore_rules_fixture("ignore-off");
+ let mut r = req(&[root.to_str().unwrap()], "needle");
+ r.respect_ignore_rules = Some(false);
+ let results = global_search(r).await.unwrap();
+ assert_eq!(
+ matched_file_names(&results),
+ vec!["ignored.sql".to_string(), "nested.sql".to_string(), "visible.sql".to_string()]
+ );
+ std::fs::remove_dir_all(&root).unwrap();
+ }
+
+ #[tokio::test]
+ async fn respect_ignore_rules_false_still_skips_pruned_directories() {
+ let root = temp_dir("ignore-pruned");
+ std::fs::create_dir_all(root.join("node_modules")).unwrap();
+ std::fs::write(root.join("node_modules").join("dep.sql"), "SELECT needle;\n").unwrap();
+ std::fs::write(root.join("main.sql"), "SELECT needle;\n").unwrap();
+ let mut r = req(&[root.to_str().unwrap()], "needle");
+ r.respect_ignore_rules = Some(false);
+ let results = global_search(r).await.unwrap();
+ assert_eq!(matched_file_names(&results), vec!["main.sql".to_string()]);
+ std::fs::remove_dir_all(&root).unwrap();
+ }
+
+ /// `root/top.sql` is depth 1, `root/a/b/deep.sql` is depth 3.
+ #[tokio::test]
+ async fn max_depth_bounds_the_walk() {
+ let root = temp_dir("max-depth");
+ std::fs::create_dir_all(root.join("a").join("b")).unwrap();
+ std::fs::write(root.join("top.sql"), "SELECT needle;\n").unwrap();
+ std::fs::write(root.join("a").join("b").join("deep.sql"), "SELECT needle;\n").unwrap();
+
+ let mut shallow = req(&[root.to_str().unwrap()], "needle");
+ shallow.max_depth = Some(1);
+ assert_eq!(matched_file_names(&global_search(shallow).await.unwrap()), vec!["top.sql".to_string()]);
+
+ let mut exact = req(&[root.to_str().unwrap()], "needle");
+ exact.max_depth = Some(3);
+ assert_eq!(
+ matched_file_names(&global_search(exact).await.unwrap()),
+ vec!["deep.sql".to_string(), "top.sql".to_string()]
+ );
+
+ // `None` keeps the walk unbounded (Quick Open behavior unchanged).
+ let unlimited = req(&[root.to_str().unwrap()], "needle");
+ assert_eq!(unlimited.max_depth, None);
+ assert_eq!(
+ matched_file_names(&global_search(unlimited).await.unwrap()),
+ vec!["deep.sql".to_string(), "top.sql".to_string()]
+ );
+ std::fs::remove_dir_all(&root).unwrap();
+ }
}