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): align library and file search scopes and previews

二丫讲梵0c7361f37b07
diff --git a/apps/desktop/src/components/layout/SqlFilePanel.vue b/apps/desktop/src/components/layout/SqlFilePanel.vue
index 40b61f5ac1..994d71c295 100644
--- a/apps/desktop/src/components/layout/SqlFilePanel.vue
+++ b/apps/desktop/src/components/layout/SqlFilePanel.vue
@@ -1,32 +1,33 @@
<script setup lang="ts">
-import { ref, computed, nextTick, onMounted, onBeforeUnmount, onUnmounted, watch, useId } from "vue";
+import { ref, computed, nextTick, onMounted, onBeforeUnmount, 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, Loader2, GripVertical, Check } from "@lucide/vue";
+import { FolderOpen, FolderClosed, FileCode, FolderPlus, ChevronRight, ChevronDown, X, Trash2, RefreshCw, FolderSearch, Copy, Play, ChevronsUpDown, ChevronsDownUp, Settings, FilePlus, Pencil, ArrowDownAZ, ArrowUpAZ, GripVertical, Check } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import SqlPanelSearch from "@/components/layout/SqlPanelSearch.vue";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import LightTooltip from "@/components/ui/LightTooltip.vue";
import HelpTooltip from "@/components/ui/tooltip/HelpTooltip.vue";
import SidebarLocateButton from "@/components/sidebar/SidebarLocateButton.vue";
+import SqlSearchMatchSnippet from "@/components/layout/SqlSearchMatchSnippet.vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { useQueryStore } from "@/stores/queryStore";
import { useConnectionStore } from "@/stores/connectionStore";
import { useSettingsStore } from "@/stores/settingsStore";
import { useToast } from "@/composables/useToast";
+import { useSqlFileContentSearch } from "@/composables/useSqlFileContentSearch";
+import type { SavedSqlLineMatch } from "@/lib/savedSql/savedSqlSearch";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
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, queryTabExternalFilePath, 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 { filterAndSortSqlFileEntries, getSqlFileSortOrder, saveSqlFileSortOrder, type SqlFileSearchMode, type SqlFileSortOrder } from "@/lib/sql/sqlFileTreeFilter";
import { orderedListSelectionIntent, type OrderedListSelectionItem } from "@/lib/selection/orderedListSelection";
import { getSqlFileOpenMode, saveSqlFileOpenMode, type SqlFileOpenMode } from "@/lib/sqlFile/sqlFileInteraction";
import { getSqlFileOrder, saveSqlFileOrder, reorderSqlFiles, remapSqlFileOrder, sqlFileParentPath, type SqlFileOrder } from "@/lib/sqlFile/sqlFileOrder";
@@ -55,9 +56,6 @@ 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(() => {
@@ -68,12 +66,47 @@ const filterSettingsOpen = ref(false);
const fileFilterDraft = ref(getSqlFileFilter());
const openMode = ref<SqlFileOpenMode>(getSqlFileOpenMode());
const openModeDraft = ref<SqlFileOpenMode>(openMode.value);
+const foldersRevision = ref(0);
const treeId = useId();
let lastClickedKey: string | null = null;
const fileFilterRegexExample = "(?i)[.](sql|ddl|sh|py)$";
-const searchText = ref("");
-const searchQuery = computed(() => searchText.value.trim().toLowerCase());
+const searchInput = ref<InstanceType<typeof SqlPanelSearch> | null>(null);
+const searchInputPending = ref(false);
+const searchMode = ref<SqlFileSearchMode>("name");
+const searchQuery = ref("");
+const {
+ searching: scanning,
+ error: searchError,
+ matchesByPath,
+ matchingPaths,
+ incomplete: searchIncomplete,
+ skippedCount,
+ skippedFiles,
+ truncated: searchTruncated,
+} = useSqlFileContentSearch(
+ () => (searchMode.value === "content" ? searchQuery.value : ""),
+ () => folders.value,
+ () => searchInputPending.value,
+);
+const searching = computed(() => searchInputPending.value || scanning.value);
+const searchIncompleteHelp = computed(() => {
+ const reasonKeys: Record<string, string> = {
+ tooLarge: "sqlFileTree.searchSkippedTooLarge",
+ unreadable: "sqlFileTree.searchSkippedUnreadable",
+ invalidEncoding: "sqlFileTree.searchSkippedInvalidEncoding",
+ outsideRoot: "sqlFileTree.searchSkippedOutsideRoot",
+ notRegularFile: "sqlFileTree.searchSkippedNotRegularFile",
+ };
+ const counts = new Map<string, number>();
+ for (const file of skippedFiles.value) {
+ const key = Object.prototype.hasOwnProperty.call(reasonKeys, file.reason) ? reasonKeys[file.reason] : "sqlFileTree.searchSkippedOther";
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ const details = [...counts].map(([key, count]) => t(key, { count }));
+ if (searchTruncated.value) details.push(t("sqlFileTree.searchPreviewLimits", { perFile: 100, total: 1000 }));
+ return [t("sqlFileTree.searchIncompleteHelp"), ...details].join("\n");
+});
const sortOrder = ref<SqlFileSortOrder>(getSqlFileSortOrder ? getSqlFileSortOrder() : "asc");
const manualOrder = ref<SqlFileOrder>(getSqlFileOrder());
const sortOptions = computed(() => [
@@ -84,181 +117,10 @@ const sortOptions = computed(() => [
const currentSortOption = computed(() => sortOptions.value.find((option) => option.order === sortOrder.value)!);
const userCollapsedDuringSearch = ref<Set<string>>(new Set());
-// ---- 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) => {
+watch([searchQuery, searchMode], () => {
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 setSortOrder(order: SqlFileSortOrder) {
if (!saveSqlFileSortOrder(order)) {
toast(t("sqlFileTree.sortSaveFailed"), 5000);
@@ -334,10 +196,10 @@ async function locateFileTarget(path: string) {
if (disposed) return;
const target = findFileTarget(path);
if (!target) return;
- if (searchText.value) {
+ if (searchInput.value?.text) {
const isVisibleNow = visibleItems.value.some((item) => item.folder === target.folder && item.type === "file" && normalizeExternalSqlPath(item.path) === target.path);
- if (!isVisibleNow) {
- searchText.value = "";
+ if (searchInputPending.value || !isVisibleNow) {
+ searchInput.value?.clear();
await nextTick();
}
}
@@ -605,7 +467,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, contentMatchPaths.value, manualOrder.value);
+ const res = filterAndSortSqlFileEntries(folder.entries, searchQuery.value, sortOrder.value, matchingPaths.value, searchMode.value, manualOrder.value);
map.set(folder.path, {
entries: res.entries,
autoExpanded: res.autoExpanded,
@@ -702,14 +564,14 @@ function collectDirPaths(entries: SqlFileEntry[], into: Set<string>) {
}
}
-async function openFile(path: string, reveal?: { line: number; column?: number }) {
+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, reveal, snapshot.encoding);
} catch (e: any) {
- if (isExternalSqlFileTooLargeError(e) && isSqlFilePath(path)) {
+ if (!reveal && isExternalSqlFileTooLargeError(e) && isSqlFilePath(path)) {
executeFile(path);
toast(t("sqlFile.largeFileExecutionOpened", { size: formatSqlFileSize(e.sizeBytes) }), 6000);
return;
@@ -718,22 +580,12 @@ async function openFile(path: string, reveal?: { line: number; column?: number }
}
}
-/** 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 });
+function handleSearchMatch(rootPath: string, path: string, match: SavedSqlLineMatch) {
+ const key = nodeKey(rootPath, "file", path);
+ selectedKeys.value = new Set();
+ activeKey.value = key;
+ selectionAnchorKey.value = key;
+ void openFile(path, { line: match.lineNumber, column: match.column });
}
// Open the App-level SQL file execution dialog with this file pre-selected so
@@ -901,10 +753,10 @@ async function scrollActiveRow() {
document.getElementById(`${treeId}-row-${activeItemIndex.value}`)?.scrollIntoView({ block: "nearest" });
}
-// Preserve identity across sorting; replace hidden or removed selection only once
-// all roots have finished loading, so refresh does not discard the active file.
-watch(visibleItems, (items, previous) => {
- if (folders.value.some((folder) => folder.loading)) return;
+// Preserve selection while content-only hits temporarily disappear during a
+// scan. Watching the pending flags also reconciles selection after an error.
+watch([visibleItems, searching, () => folders.value.some((folder) => folder.loading || folder.refreshing)], ([items, searchPending, foldersPending], [previous]) => {
+ if (searchPending || foldersPending) return;
const ids = new Set(items.map((item) => item.id));
selectedKeys.value = new Set([...selectedKeys.value].filter((key) => ids.has(key)));
if (activeKey.value && !ids.has(activeKey.value)) {
@@ -1417,14 +1269,13 @@ function clearContextTarget() {
</div>
<div v-if="folders.length > 0" class="border-b shrink-0 px-2 py-1">
- <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>
- </div>
+ <SqlPanelSearch ref="searchInput" v-model:mode="searchMode" panel="file" @query="searchQuery = $event" @pending="searchInputPending = $event" />
+ <p v-if="searching" class="mt-1 text-xs text-muted-foreground" role="status" aria-live="polite">{{ t("sqlFileTree.searching") }}</p>
+ <p v-else-if="searchError" class="mt-1 text-xs text-destructive" role="status">{{ t("sqlFileTree.searchFailed", { message: translateBackendError(t, searchError) }) }}</p>
+ <p v-else-if="searchIncomplete" class="mt-1 text-xs text-muted-foreground" role="status">
+ {{ t("sqlFileTree.searchIncomplete", { skipped: skippedCount }) }}
+ <HelpTooltip :label="searchIncompleteHelp" side="bottom" :side-offset="4" trigger-class="ml-1 align-middle" content-class="max-w-[320px] whitespace-pre-line" />
+ </p>
</div>
<CustomContextMenu :items="contextMenuItems" @close="clearContextTarget">
@@ -1512,7 +1363,7 @@ 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 && !contentSearchPending && 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 && !searching && !searchError && !searchIncomplete && 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>
@@ -1595,15 +1446,15 @@ function clearContextTarget() {
</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)"
+ v-if="searchMode === 'content' && !entry.is_dir && matchesByPath.has(normalizeExternalSqlPath(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)"
+ :matches="matchesByPath.get(normalizeExternalSqlPath(entry.path))!.matches"
+ :total-matches="matchesByPath.get(normalizeExternalSqlPath(entry.path))!.totalMatches"
+ :preview-limit="matchesByPath.get(normalizeExternalSqlPath(entry.path))!.matches.length"
+ :query="searchQuery"
+ :depth="depth + 1"
+ @select-match="handleSearchMatch(folder.path, entry.path, $event)"
/>
</template>
</div>
diff --git a/apps/desktop/src/components/layout/SqlLibraryPanel.vue b/apps/desktop/src/components/layout/SqlLibraryPanel.vue
index 6a26e83d9a..7a963dda5b 100644
--- a/apps/desktop/src/components/layout/SqlLibraryPanel.vue
+++ b/apps/desktop/src/components/layout/SqlLibraryPanel.vue
@@ -27,13 +27,13 @@ import {
LocateFixed,
Pencil,
Play,
- Search,
Trash2,
Upload,
X,
} from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import SqlPanelSearch from "@/components/layout/SqlPanelSearch.vue";
import { SearchableSelect } from "@/components/ui/searchable-select";
import CustomContextMenu, { type ContextMenuItem as CtxMenuItem } from "@/components/ui/CustomContextMenu.vue";
import ConnectionTreeSelect from "@/components/connection/ConnectionTreeSelect.vue";
@@ -87,14 +87,33 @@ type DragItemType = "folder" | "file" | "unfiled";
type DropPosition = "before" | "after" | "inside";
const activeConnectionIds = computed(() => new Set(connectionStore.connections.map((c) => c.id)));
-const searchText = ref("");
-const searchQuery = computed(() => searchText.value.trim().toLowerCase());
-
-watch(searchText, (text) => {
- if (text.trim()) {
- void savedSqlStore.ensureAllFilesLoaded();
+const searchInput = ref<InstanceType<typeof SqlPanelSearch> | null>(null);
+const searchInputPending = ref(false);
+const searchQuery = ref("");
+
+const searchMode = ref<"name" | "content">("name");
+const loadingSearchContent = ref(false);
+const unloadedSearchFiles = computed(() => savedSqlStore.allFiles.filter((file) => file.sqlLoaded === false));
+const contentSearchActive = computed(() => searchMode.value === "content" && !!searchQuery.value);
+
+async function loadSearchContent() {
+ if (searchInputPending.value || loadingSearchContent.value || !contentSearchActive.value || unloadedSearchFiles.value.length === 0) return;
+ loadingSearchContent.value = true;
+ try {
+ await savedSqlStore.ensureAllFilesLoaded();
+ } catch {
+ // Unloaded files remain visible in the incomplete-search status below.
+ } finally {
+ loadingSearchContent.value = false;
}
-});
+}
+
+watch(
+ () => [searchMode.value, searchQuery.value, searchInputPending.value, unloadedSearchFiles.value.map((file) => file.id).join("\n")],
+ () => {
+ void loadSearchContent();
+ },
+);
// Sort mode: "folder" (manual sibling order) or "date" (updated date among siblings)
const sortMode = ref<"folder" | "date">("folder");
@@ -355,13 +374,13 @@ async function openSqlStorageDirectory() {
function fileMatchesQuery(file: SavedSqlFile) {
const q = searchQuery.value;
if (!q) return true;
- return [file.name, file.database, file.schema, file.sql, getConnectionLabel(file.connectionId)].filter(Boolean).some((value) => String(value).toLowerCase().includes(q));
+ return (searchMode.value === "name" ? file.name : file.sql).toLowerCase().includes(q);
}
function folderMatchesQuery(folder: SavedSqlFolder) {
const q = searchQuery.value;
if (!q) return true;
- return folder.name.toLowerCase().includes(q);
+ return searchMode.value === "name" && folder.name.toLowerCase().includes(q);
}
function childFolders(parentFolderId?: string) {
@@ -380,7 +399,7 @@ function folderBranchMatchesQuery(folder: SavedSqlFolder) {
function filesInFolder(folderId: string) {
const folder = savedSqlStore.allFolders.find((item) => item.id === folderId);
- const includeAllFilesForMatchedFolder = !!folder && !!searchQuery.value && folder.name.toLowerCase().includes(searchQuery.value);
+ const includeAllFilesForMatchedFolder = !!folder && !!searchQuery.value && folderMatchesQuery(folder);
return savedSqlStore.filesInFolder(folderId).filter((file) => includeAllFilesForMatchedFolder || fileMatchesQuery(file));
}
@@ -464,7 +483,7 @@ async function openNewFolderInput(parentFolderId?: string) {
}
try {
const folder = await savedSqlStore.createFolder(connectionId, t("savedSql.newFolderDefault"), parent?.id);
- searchText.value = "";
+ searchInput.value?.clear();
startRenameFolder(folder);
} catch (e: any) {
toast(t("savedSql.createFolderFailed", { message: e?.message || String(e) }), 5000);
@@ -1607,22 +1626,12 @@ function showDropInside(targetId: string) {
</div>
<div class="border-b shrink-0 px-2 py-1">
- <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-library-search
- v-model="searchText"
- @focus="savedSqlStore.ensureAllFilesLoaded()"
- 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')"
- />
- <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>
- </div>
+ <SqlPanelSearch ref="searchInput" v-model:mode="searchMode" panel="library" @query="searchQuery = $event" @pending="searchInputPending = $event" />
+ <p v-if="searchInputPending || (contentSearchActive && loadingSearchContent)" class="mt-1 text-xs text-muted-foreground" role="status" aria-live="polite">{{ t("sqlFileTree.searching") }}</p>
+ <p v-else-if="contentSearchActive && unloadedSearchFiles.length" class="mt-1 text-xs text-destructive" role="status">
+ {{ t("sqlLibrary.searchContentIncomplete", { count: unloadedSearchFiles.length }) }}
+ <button type="button" class="underline" @click="loadSearchContent">{{ t("common.retry") }}</button>
+ </p>
</div>
<div class="min-h-0 flex-1 overflow-y-auto py-1">
@@ -1703,6 +1712,7 @@ function showDropInside(targetId: string) {
<div
class="relative flex cursor-default items-center gap-1 py-1.5 pr-2 text-[13px] group"
:style="{ paddingLeft: `${8 + row.depth * 16}px` }"
+ :data-sql-library-file="row.file.id"
:class="[fileRowClass(row.file.id), isDraggingItem(row.file.id) ? 'opacity-50' : '']"
@mousedown="handleDragMouseDown($event, row.file.id, 'file')"
@mousemove="updateDropTarget($event, row.file.id, 'file')"
@@ -1736,7 +1746,7 @@ function showDropInside(targetId: string) {
<span v-else class="dbx-sql-library-drag-label min-w-0 flex-1 truncate" :title="fileTitleLabel(row.file)" :style="fileTitleStyle(row.file)">{{ row.file.name }}</span>
<span class="min-w-0 max-w-[45%] shrink truncate text-[13px]" :class="fileMetaClass(row.file.id)" :title="getConnectionLabel(row.file.connectionId)">[{{ getConnectionLabel(row.file.connectionId) }}]</span>
</div>
- <SqlLibrarySearchSnippet v-if="searchQuery" :file="row.file" :query="searchQuery" :depth="row.depth" @select-match="(match) => handleMatchClick(row.file, match)" />
+ <SqlLibrarySearchSnippet v-if="contentSearchActive" :file="row.file" :query="searchQuery" :depth="row.depth" @select-match="(match) => handleMatchClick(row.file, match)" />
</template>
</div>
@@ -1745,9 +1755,9 @@ function showDropInside(targetId: string) {
<p class="text-[13px]">{{ t("common.loading") }}</p>
</div>
- <div v-else-if="!hasAnyVisibleItem" class="flex h-full flex-col items-center justify-center gap-2 text-muted-foreground">
+ <div v-else-if="!hasAnyVisibleItem && !(searchInputPending || (contentSearchActive && (loadingSearchContent || unloadedSearchFiles.length)))" class="flex h-full flex-col items-center justify-center gap-2 text-muted-foreground">
<Library class="h-8 w-8 opacity-30" />
- <p class="text-[13px]">{{ t("sqlLibrary.empty") }}</p>
+ <p class="text-[13px]">{{ t(searchQuery ? "grid.noSearchResults" : "sqlLibrary.empty") }}</p>
</div>
</div>
</template>
diff --git a/apps/desktop/src/components/layout/SqlLibrarySearchSnippet.vue b/apps/desktop/src/components/layout/SqlLibrarySearchSnippet.vue
index a33154e253..414b2ff7f7 100644
--- a/apps/desktop/src/components/layout/SqlLibrarySearchSnippet.vue
+++ b/apps/desktop/src/components/layout/SqlLibrarySearchSnippet.vue
@@ -43,5 +43,15 @@ const totalMatches = computed(() => searchResult.value.totalMatches);
<template>
<!-- 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)" />
+ <SqlSearchMatchSnippet
+ class="dbx-sql-library-snippets"
+ :query="query"
+ :matches="matches"
+ :preview-limit="EXPANDED_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/SqlPanelSearch.vue b/apps/desktop/src/components/layout/SqlPanelSearch.vue
new file mode 100644
index 0000000000..e34ef4675b
--- /dev/null
+++ b/apps/desktop/src/components/layout/SqlPanelSearch.vue
@@ -0,0 +1,106 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { Search, X } from "@lucide/vue";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import type { SqlFileSearchMode } from "@/lib/sql/sqlFileTreeFilter";
+
+const props = defineProps<{ mode: SqlFileSearchMode; panel: "file" | "library" }>();
+const emit = defineEmits<{
+ "update:mode": [mode: SqlFileSearchMode];
+ query: [query: string];
+ pending: [pending: boolean];
+}>();
+const { t } = useI18n();
+// Keep draft keystrokes local: the large parent tree only sees committed queries.
+const text = ref("");
+const composing = ref(false);
+const mode = computed({
+ get: () => props.mode,
+ set: (value: SqlFileSearchMode) => {
+ if (value === props.mode) return;
+ // Suspend before the parent changes scope, so its old query cannot start a scan.
+ setPending(true);
+ emit("update:mode", value);
+ },
+});
+const query = computed(() => text.value.trim().toLowerCase());
+const inputAttrs = computed(() => ({ [`data-sql-${props.panel}-search`]: "" }));
+const modeAttrs = computed(() => ({ [`data-sql-${props.panel}-search-mode`]: "" }));
+let timer: ReturnType<typeof setTimeout> | undefined;
+let pending = false;
+
+function setPending(value: boolean) {
+ if (pending === value) return;
+ pending = value;
+ emit("pending", value);
+}
+function commit() {
+ clearTimeout(timer);
+ emit("query", query.value);
+ setPending(false);
+}
+function submit(event: KeyboardEvent) {
+ if (!composing.value && !event.isComposing && event.keyCode !== 229) commit();
+}
+function clear() {
+ text.value = "";
+ commit();
+}
+watch(
+ [query, () => props.mode, composing],
+ () => {
+ clearTimeout(timer);
+ if (composing.value) {
+ setPending(props.mode === "content");
+ return;
+ }
+ if (props.mode === "name" || !query.value) {
+ commit();
+ return;
+ }
+ // Invalidate in-flight results once, without rerendering the parent per key.
+ setPending(true);
+ timer = setTimeout(commit, 500);
+ },
+ { flush: "sync" },
+);
+onBeforeUnmount(() => {
+ clearTimeout(timer);
+ emit("query", "");
+ setPending(false);
+});
+defineExpose({ text, clear });
+</script>
+
+<template>
+ <div class="flex items-center gap-1">
+ <Select v-model="mode">
+ <SelectTrigger v-bind="modeAttrs" class="data-[size=default]:h-6 max-w-[45%] shrink-0 rounded px-1.5 py-0 text-xs" :aria-label="t('sqlFileTree.searchMode')">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="name">{{ t("sqlFileTree.searchByName") }}</SelectItem>
+ <SelectItem value="content">{{ t("sqlFileTree.searchByContent") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <div class="relative min-w-0 flex-1">
+ <Search class="absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-muted-foreground" />
+ <input
+ v-bind="inputAttrs"
+ v-model="text"
+ 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(mode === 'name' ? 'sqlFileTree.searchPlaceholder' : 'sqlFileTree.searchContentPlaceholder')"
+ @keydown.enter="submit"
+ @compositionstart="composing = true"
+ @compositionend="composing = false"
+ />
+ <button v-if="text" type="button" class="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground" @click="clear">
+ <X class="h-3 w-3" />
+ </button>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/layout/SqlSearchMatchSnippet.vue b/apps/desktop/src/components/layout/SqlSearchMatchSnippet.vue
index d452b9e6db..f54fafed56 100644
--- a/apps/desktop/src/components/layout/SqlSearchMatchSnippet.vue
+++ b/apps/desktop/src/components/layout/SqlSearchMatchSnippet.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { computed, ref } from "vue";
+import { computed, ref, watch, type ObjectDirective } from "vue";
import { useI18n } from "vue-i18n";
import { formatMatchTooltip, type SavedSqlLineMatch } from "@/lib/savedSql/savedSqlSearch";
@@ -12,12 +12,16 @@ const props = withDefaults(
defineProps<{
matches: SavedSqlLineMatch[];
totalMatches: number;
+ query: string;
+ /** Maximum available previews, including those built lazily on expansion. */
+ previewLimit?: number;
depth?: number;
initialVisible?: number;
}>(),
{
depth: 0,
initialVisible: 3,
+ previewLimit: 100,
},
);
@@ -32,7 +36,47 @@ 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);
+const hasHiddenMatches = computed(() => Math.min(props.totalMatches, props.previewLimit) > props.initialVisible);
+const previewLimited = computed(() => props.totalMatches > props.previewLimit);
+
+// Measure rendered pixels so Chinese text, indentation and sidebar resizing
+// all keep the first highlight visible without changing its editor position.
+function centerFirstMatch(viewport: HTMLElement) {
+ const mark = viewport.querySelector("mark");
+ if (!mark || viewport.clientWidth === 0) {
+ viewport.scrollLeft = 0;
+ return;
+ }
+ const bounds = mark.getBoundingClientRect();
+ const matchStart = bounds.left - viewport.getBoundingClientRect().left + viewport.scrollLeft;
+ const leadingSpace = Math.max(0, (viewport.clientWidth - bounds.width) / 2);
+ viewport.scrollLeft = Math.max(0, matchStart - leadingSpace);
+}
+
+const previewObservers = new WeakMap<HTMLElement, ResizeObserver>();
+const vCenterSearchMatch: ObjectDirective<HTMLElement> = {
+ mounted(viewport) {
+ centerFirstMatch(viewport);
+ if (typeof ResizeObserver !== "undefined") {
+ const observer = new ResizeObserver(() => centerFirstMatch(viewport));
+ observer.observe(viewport);
+ previewObservers.set(viewport, observer);
+ }
+ },
+ updated: centerFirstMatch,
+ unmounted(viewport) {
+ previewObservers.get(viewport)?.disconnect();
+ previewObservers.delete(viewport);
+ },
+};
+
+watch(
+ () => props.query,
+ () => {
+ expanded.value = false;
+ emit("expandedChange", false);
+ },
+);
function toggleExpanded() {
expanded.value = !expanded.value;
@@ -45,7 +89,7 @@ function handleSnippetClick(match: SavedSqlLineMatch) {
</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-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 @dblclick.stop>
<div
v-for="match in visibleMatches"
:key="match.lineNumber"
@@ -54,7 +98,7 @@ function handleSnippetClick(match: SavedSqlLineMatch) {
@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">
+ <span v-center-search-match class="min-w-0 flex-1 overflow-hidden whitespace-nowrap">
<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>
@@ -67,5 +111,8 @@ function handleSnippetClick(match: SavedSqlLineMatch) {
{{ expanded ? t("sqlLibrary.collapseMatches") : t("sqlLibrary.moreMatches", { count: totalMatches - initialVisible }) }}
</button>
</div>
+ <p v-if="previewLimited" class="pt-0.5 text-[11px] text-muted-foreground">
+ {{ t("sqlLibrary.matchPreviewLimit", { limit: previewLimit, total: totalMatches }) }}
+ </p>
</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
index 0f548f1939..f2454b6a5e 100644
--- a/apps/desktop/src/components/layout/__tests__/SqlFilePanel.contentSearch.spec.ts
+++ b/apps/desktop/src/components/layout/__tests__/SqlFilePanel.contentSearch.spec.ts
@@ -4,12 +4,12 @@ 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 type { SqlFileContentSearchResult } from "@/lib/backend/api";
import { useQueryStore } from "@/stores/queryStore";
const mocks = vi.hoisted(() => ({
isTauri: true,
- globalSearch: vi.fn(async (_request: unknown): Promise<GlobalSearchMatch[]> => []),
+ search: vi.fn(async (..._args: unknown[]): Promise<SqlFileContentSearchResult> => ({ files: [], skippedFiles: [], truncated: false })),
readSnapshot: vi.fn(async () => ({ content: "SELECT 1;", version: { mtimeMs: 1, size: 9 } })),
}));
@@ -47,9 +47,11 @@ 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,
+ searchSqlFileContents: mocks.search,
}));
+vi.mock("@/components/ui/select", () => import("./sqlSearchTestUtils"));
+import { changeSearchMode } from "./sqlSearchTestUtils";
import SqlFilePanel from "../SqlFilePanel.vue";
const mounted: Array<{ app: App; host: HTMLElement }> = [];
@@ -75,19 +77,33 @@ function typeQuery(host: HTMLElement, value: string) {
input.dispatchEvent(new Event("input"));
}
-function hit(overrides: Partial<GlobalSearchMatch> & { path: string; line: number; column: number }): GlobalSearchMatch {
+function result(path: string, lines = [3], column = 8): SqlFileContentSearchResult {
return {
- fileName: overrides.path.split("/").pop() ?? overrides.path,
- matchText: "needle",
- lineText: "SELECT needle FROM t",
- ...overrides,
+ files: [
+ {
+ path,
+ totalMatches: lines.length,
+ matches: lines.map((lineNumber) => ({
+ lineNumber,
+ column,
+ lineText: "SELECT needle FROM t",
+ segments: [
+ { text: "SELECT ", matched: false },
+ { text: "needle", matched: true },
+ { text: " FROM t", matched: false },
+ ],
+ })),
+ },
+ ],
+ skippedFiles: [],
+ truncated: false,
};
}
beforeEach(() => {
mocks.isTauri = true;
- mocks.globalSearch.mockReset();
- mocks.globalSearch.mockResolvedValue([]);
+ mocks.search.mockReset();
+ mocks.search.mockResolvedValue({ files: [], skippedFiles: [], truncated: false });
mocks.readSnapshot.mockClear();
});
@@ -102,8 +118,9 @@ afterEach(() => {
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 })]);
+ mocks.search.mockResolvedValue(result("/sql/queries/02_orders.sql"));
+ await changeSearchMode(host, "content");
typeQuery(host, "needle");
await vi.waitFor(() => expect(host.querySelector('[data-sql-file-path="/sql/queries/02_orders.sql"]')).not.toBeNull());
@@ -119,17 +136,16 @@ describe("SqlFilePanel content search", () => {
// 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 }));
+ // Search uses the exact same file filter as the tree.
+ expect(mocks.search).toHaveBeenCalledWith(["/sql"], "needle", "*.sql");
});
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 })]);
+ mocks.search.mockResolvedValue(result("/sql/queries/02_orders.sql"));
const openExternalSqlFile = vi.spyOn(queryStore, "openExternalSqlFile");
+ await changeSearchMode(host, "content");
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');
@@ -150,8 +166,9 @@ describe("SqlFilePanel content search", () => {
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 })));
+ mocks.search.mockResolvedValue(result("/sql/queries/02_orders.sql", [1, 2, 3, 4, 5], 1));
+ await changeSearchMode(host, "content");
typeQuery(host, "needle");
const snippet = await vi.waitFor(() => {
const element = host.querySelector<HTMLElement>('[data-sql-file-content-snippet="/sql/queries/02_orders.sql"]');
@@ -169,36 +186,41 @@ describe("SqlFilePanel content search", () => {
it("debounces lookups so fast typing issues a single final request", async () => {
const { host } = await mountPanel();
+ await changeSearchMode(host, "content");
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" }));
+ expect(mocks.search).not.toHaveBeenCalled();
+ await vi.waitFor(() => expect(mocks.search).toHaveBeenCalledTimes(1));
+ expect(mocks.search).toHaveBeenCalledWith(["/sql"], "needle", "*.sql");
});
it("discards results from a superseded query", async () => {
const { host } = await mountPanel();
- let resolveFirst: ((matches: GlobalSearchMatch[]) => void) | undefined;
- mocks.globalSearch.mockImplementationOnce(
+ let resolveFirst: ((matches: SqlFileContentSearchResult) => void) | undefined;
+ mocks.search.mockImplementationOnce(
() =>
- new Promise<GlobalSearchMatch[]>((resolve) => {
+ new Promise<SqlFileContentSearchResult>((resolve) => {
resolveFirst = resolve;
}),
);
- mocks.globalSearch.mockResolvedValueOnce([hit({ path: "/sql/migrations/01_init.sql", line: 2, column: 1 })]);
+ mocks.search.mockResolvedValueOnce(result("/sql/migrations/01_init.sql", [2], 1));
+ await changeSearchMode(host, "content");
typeQuery(host, "needle");
- await vi.waitFor(() => expect(mocks.globalSearch).toHaveBeenCalledTimes(1));
+ await vi.waitFor(() => expect(mocks.search).toHaveBeenCalledTimes(1));
- // Second query starts (and finishes) before the first response arrives.
+ // Disk scans are serialized; the latest query waits for the in-flight scan.
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();
+ expect(host.querySelector('[data-sql-file-path="/sql/queries/02_orders.sql"]')).toBeNull();
+ resolveFirst!(result("/sql/queries/02_orders.sql", [1], 1));
await nextTick();
await nextTick();
+ // Invalidate on the first new keystroke, before the debounce commits "other".
+ expect(host.querySelector("[data-sql-file-content-snippet]")).toBeNull();
+ await vi.waitFor(() => expect(host.querySelector('[data-sql-file-path="/sql/migrations/01_init.sql"]')).not.toBeNull());
// 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();
@@ -206,8 +228,9 @@ describe("SqlFilePanel content search", () => {
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 })]);
+ mocks.search.mockResolvedValue(result("/sql/queries/02_orders.sql", [1], 1));
+ await changeSearchMode(host, "content");
typeQuery(host, "needle");
await vi.waitFor(() => expect(host.querySelector("[data-sql-file-content-snippet]")).not.toBeNull());
@@ -219,7 +242,32 @@ describe("SqlFilePanel content search", () => {
expect(host.querySelector("[data-sql-file-content-snippet]")).toBeNull();
});
- it("degrades to name-only filtering outside the desktop runtime", async () => {
+ it("keeps the two scopes separate and removes content snippets on switching to names", async () => {
+ const { host } = await mountPanel();
+ typeQuery(host, "orders");
+ await nextTick();
+ expect(host.querySelector('[data-sql-file-path="/sql/queries/02_orders.sql"]')).not.toBeNull();
+ expect(mocks.search).not.toHaveBeenCalled();
+ mocks.search.mockResolvedValue(result("/sql/alpha.sql"));
+ await changeSearchMode(host, "content");
+ await vi.waitFor(() => expect(host.querySelector('[data-sql-file-path="/sql/alpha.sql"]')).not.toBeNull());
+ expect(host.querySelector('[data-sql-file-path="/sql/queries/02_orders.sql"]')).toBeNull();
+ await changeSearchMode(host, "name");
+ expect(host.querySelector('[data-sql-file-path="/sql/queries/02_orders.sql"]')).not.toBeNull();
+ expect(host.querySelector("[data-sql-file-content-snippet]")).toBeNull();
+ });
+
+ it("reports a failed content search without silently matching names", async () => {
+ const { host } = await mountPanel();
+ mocks.search.mockRejectedValue(new Error("Search unavailable"));
+ await changeSearchMode(host, "content");
+ typeQuery(host, "orders");
+ await vi.waitFor(() => expect(host.textContent).toContain("Search unavailable"));
+ expect(host.querySelector('[data-sql-file-path="/sql/queries/02_orders.sql"]')).toBeNull();
+ expect(host.querySelector("[data-sql-file-empty-search]")).toBeNull();
+ });
+
+ it("defaults to name filtering without scanning, including outside the desktop runtime", async () => {
mocks.isTauri = false;
const { host } = await mountPanel();
@@ -229,6 +277,6 @@ describe("SqlFilePanel content search", () => {
// 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();
+ expect(mocks.search).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/components/layout/__tests__/SqlLibraryPanel.search.spec.ts b/apps/desktop/src/components/layout/__tests__/SqlLibraryPanel.search.spec.ts
new file mode 100644
index 0000000000..8c28141432
--- /dev/null
+++ b/apps/desktop/src/components/layout/__tests__/SqlLibraryPanel.search.spec.ts
@@ -0,0 +1,113 @@
+// @vitest-environment happy-dom
+import { createApp, nextTick, type App } from "vue";
+import { createPinia, setActivePinia } from "pinia";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import { useSavedSqlStore } from "@/stores/savedSqlStore";
+import type { SavedSqlFile } from "@/types/database";
+import { changeSearchMode } from "./sqlSearchTestUtils";
+
+vi.mock("@/components/ui/select", () => import("./sqlSearchTestUtils"));
+vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
+import SqlLibraryPanel from "../SqlLibraryPanel.vue";
+
+const mounted: Array<{ app: App; host: HTMLElement }> = [];
+const timestamp = "2026-10-01T00:00:00Z";
+function file(id: string, name: string, sql: string, sqlLoaded = true): SavedSqlFile {
+ return { id, name, sql, sqlLoaded, connectionId: "", database: "metadata-only", createdAt: timestamp, updatedAt: timestamp };
+}
+
+async function mountPanel() {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ const store = useSavedSqlStore();
+ store.loadState = "loaded";
+ store.files = [file("name", "needle.sql", "SELECT 1"), file("body", "other.sql", "", false)];
+ const load = vi.spyOn(store, "ensureAllFilesLoaded").mockResolvedValue(undefined);
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(SqlLibraryPanel);
+ app.use(pinia);
+ app.use(i18n);
+ app.mount(host);
+ mounted.push({ app, host });
+ await nextTick();
+ return { host, store, load };
+}
+async function typeQuery(host: HTMLElement, query: string) {
+ const input = host.querySelector<HTMLInputElement>("[data-sql-library-search]")!;
+ input.value = query;
+ input.dispatchEvent(new Event("input"));
+ await nextTick();
+}
+function visibleFiles(host: HTMLElement) {
+ return [...host.querySelectorAll("[data-sql-library-file]")].map((row) => row.getAttribute("data-sql-library-file"));
+}
+afterEach(() => {
+ for (const { app, host } of mounted.splice(0)) {
+ app.unmount();
+ host.remove();
+ }
+ vi.restoreAllMocks();
+});
+
+describe("SQL library search scopes", () => {
+ it("defaults to filenames without loading content, even on focus", async () => {
+ const { host, load } = await mountPanel();
+ host.querySelector<HTMLInputElement>("[data-sql-library-search]")!.focus();
+ await typeQuery(host, "needle");
+ expect(visibleFiles(host)).toEqual(["name"]);
+ expect(load).not.toHaveBeenCalled();
+ expect(host.querySelector(".dbx-sql-library-snippets")).toBeNull();
+ await typeQuery(host, "metadata-only");
+ expect(visibleFiles(host)).toEqual([]);
+ });
+
+ it("loads only for content searches and excludes matching names and directories", async () => {
+ const { host, store, load } = await mountPanel();
+ store.folders = [{ id: "folder", connectionId: "", name: "needle", createdAt: timestamp, updatedAt: timestamp }];
+ store.files.push({ ...file("unrelated", "unrelated.sql", "SELECT 1"), folderId: "folder" });
+ load.mockImplementation(async () => {
+ store.files = store.files.map((entry) => (entry.id === "body" ? { ...entry, sql: "SELECT needle", sqlLoaded: true } : entry));
+ });
+ await changeSearchMode(host, "content");
+ expect(load).not.toHaveBeenCalled();
+ await typeQuery(host, "needle");
+ await vi.waitFor(() => expect(visibleFiles(host)).toEqual(["body"]));
+ expect(load).toHaveBeenCalledTimes(1);
+ expect(host.querySelector("mark")?.textContent).toBe("needle");
+ await changeSearchMode(host, "name");
+ expect(visibleFiles(host)).toContain("name");
+ expect(visibleFiles(host)).not.toContain("body");
+ expect(host.querySelector(".dbx-sql-library-snippets")).toBeNull();
+ });
+
+ it("shows pending and incomplete states, allows retry, and does not claim no matches", async () => {
+ const { host, store, load } = await mountPanel();
+ let complete!: () => void;
+ load.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ complete = resolve;
+ }),
+ );
+ await changeSearchMode(host, "content");
+ await typeQuery(host, "needle");
+ expect(host.textContent).toContain(i18n.global.t("sqlFileTree.searching"));
+ await vi.waitFor(() => expect(load).toHaveBeenCalledTimes(1));
+ await typeQuery(host, "other");
+ host.querySelector<HTMLInputElement>("[data-sql-library-search]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter" }));
+ await nextTick();
+ expect(load).toHaveBeenCalledTimes(1);
+ complete();
+ await vi.waitFor(() => expect(host.textContent).toContain(i18n.global.t("sqlLibrary.searchContentIncomplete", { count: 1 })));
+ expect(host.textContent).not.toContain(i18n.global.t("grid.noSearchResults"));
+ load.mockImplementationOnce(async () => {
+ store.files = store.files.map((entry) => ({ ...entry, sqlLoaded: true }));
+ });
+ const retry = [...host.querySelectorAll("button")].find((button) => button.textContent?.trim() === i18n.global.t("common.retry"));
+ retry!.click();
+ await vi.waitFor(() => expect(host.textContent).toContain(i18n.global.t("grid.noSearchResults")));
+ expect(load).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/components/layout/__tests__/SqlLibrarySearchSnippet.spec.ts b/apps/desktop/src/components/layout/__tests__/SqlLibrarySearchSnippet.spec.ts
index 363f02f0f8..e631f11f02 100644
--- a/apps/desktop/src/components/layout/__tests__/SqlLibrarySearchSnippet.spec.ts
+++ b/apps/desktop/src/components/layout/__tests__/SqlLibrarySearchSnippet.spec.ts
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
-import { createApp, nextTick, type App } from "vue";
+import { createApp, h, nextTick, reactive, ref, unref, type App, type Ref } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
@@ -22,14 +22,12 @@ function sampleFile(sql: string): SavedSqlFile {
};
}
-function mountSnippet(file: SavedSqlFile, query: string, onSelectMatch?: (match: any) => void) {
+function mountSnippet(file: SavedSqlFile, query: string | Ref<string>, onSelectMatch?: (match: any) => void) {
setActivePinia(createPinia());
const host = document.createElement("div");
document.body.appendChild(host);
- const app = createApp(SqlLibrarySearchSnippet, {
- file,
- query,
- onSelectMatch,
+ const app = createApp({
+ render: () => h(SqlLibrarySearchSnippet, { file, query: unref(query), onSelectMatch }),
});
app.use(i18n);
app.mount(host);
@@ -128,4 +126,29 @@ describe("SqlLibrarySearchSnippet", () => {
snippetRows = host.querySelectorAll(".group\\/snippet");
expect(snippetRows).toHaveLength(3);
});
+ it("keeps expanded results across refreshes but resets for a different query", async () => {
+ const file = reactive(sampleFile(Array.from({ length: 5 }, () => "SELECT needle").join("\n")));
+ const query = ref("needle");
+ const host = mountSnippet(file, query);
+ await nextTick();
+ host.querySelector<HTMLButtonElement>("button")!.click();
+ await nextTick();
+ expect(host.querySelectorAll("mark")).toHaveLength(5);
+ file.sql += "\nSELECT needle";
+ await nextTick();
+ expect(host.querySelectorAll("mark")).toHaveLength(6);
+ query.value = "SELECT";
+ await nextTick();
+ expect(host.querySelectorAll("mark")).toHaveLength(3);
+ });
+
+ it("reports the preview cap without understating matching line counts", async () => {
+ const host = mountSnippet(sampleFile(Array.from({ length: 150 }, () => "SELECT needle").join("\n")), "needle");
+ await nextTick();
+ expect(host.querySelector<HTMLButtonElement>("button")?.textContent).toContain("147");
+ expect(host.textContent).toContain(i18n.global.t("sqlLibrary.matchPreviewLimit", { limit: 100, total: 150 }));
+ host.querySelector<HTMLButtonElement>("button")!.click();
+ await nextTick();
+ expect(host.querySelectorAll("mark")).toHaveLength(100);
+ });
});
diff --git a/apps/desktop/src/components/layout/__tests__/SqlPanelSearch.spec.ts b/apps/desktop/src/components/layout/__tests__/SqlPanelSearch.spec.ts
new file mode 100644
index 0000000000..5555b9ae47
--- /dev/null
+++ b/apps/desktop/src/components/layout/__tests__/SqlPanelSearch.spec.ts
@@ -0,0 +1,118 @@
+// @vitest-environment happy-dom
+import { createApp, h, nextTick, ref, type App } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import type { SqlFileSearchMode } from "@/lib/sql/sqlFileTreeFilter";
+import { changeSearchMode } from "./sqlSearchTestUtils";
+vi.mock("@/components/ui/select", () => import("./sqlSearchTestUtils"));
+import SqlPanelSearch from "../SqlPanelSearch.vue";
+
+const mounted: Array<{ app: App; host: HTMLElement }> = [];
+async function mountSearch(initialMode: SqlFileSearchMode = "content") {
+ const mode = ref(initialMode);
+ const onQuery = vi.fn();
+ const onPending = vi.fn();
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp({
+ render: () =>
+ h(SqlPanelSearch, {
+ panel: "file",
+ mode: mode.value,
+ "onUpdate:mode": (value: SqlFileSearchMode) => {
+ mode.value = value;
+ },
+ onQuery,
+ onPending,
+ }),
+ });
+ app.use(i18n);
+ app.mount(host);
+ mounted.push({ app, host });
+ await nextTick();
+ const input = host.querySelector<HTMLInputElement>("input")!;
+ async function type(value: string) {
+ input.value = value;
+ input.dispatchEvent(new Event("input"));
+ await nextTick();
+ }
+ return { host, input, type, onQuery, onPending };
+}
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => {
+ for (const { app, host } of mounted.splice(0)) {
+ app.unmount();
+ host.remove();
+ }
+ vi.useRealTimers();
+});
+
+describe("SqlPanelSearch", () => {
+ it("keeps content keystrokes local until 500 ms after the final input", async () => {
+ const { type, input, onQuery, onPending } = await mountSearch();
+ await type("sel");
+ await vi.advanceTimersByTimeAsync(300);
+ await type("select");
+ expect(input.value).toBe("select");
+ await vi.advanceTimersByTimeAsync(499);
+ expect(onQuery).not.toHaveBeenCalled();
+ expect(onPending.mock.calls).toEqual([[true]]);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(onQuery.mock.calls).toEqual([["select"]]);
+ expect(onPending.mock.calls).toEqual([[true], [false]]);
+ await type("select from");
+ // The parent continues showing its last committed query while typing.
+ expect(onQuery).toHaveBeenCalledTimes(1);
+ });
+
+ it("commits immediately on Enter and does not fire again at the old deadline", async () => {
+ const { type, input, onQuery } = await mountSearch();
+ await type("select");
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter" }));
+ expect(onQuery.mock.calls).toEqual([["select"]]);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(onQuery).toHaveBeenCalledTimes(1);
+ });
+
+ it("pauses for IME composition, including the Enter used to confirm a candidate", async () => {
+ const { type, input, onQuery } = await mountSearch();
+ await type("sel");
+ input.dispatchEvent(new CompositionEvent("compositionstart"));
+ await nextTick();
+ await vi.advanceTimersByTimeAsync(600);
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", isComposing: true }));
+ expect(onQuery).not.toHaveBeenCalled();
+ input.value = "请求方式";
+ input.dispatchEvent(new CompositionEvent("compositionend"));
+ await nextTick();
+ await vi.advanceTimersByTimeAsync(500);
+ expect(onQuery.mock.calls).toEqual([["请求方式"]]);
+ });
+
+ it("keeps filename filtering immediate and cancels pending content work on switching back", async () => {
+ const { host, type, onQuery, onPending } = await mountSearch("name");
+ await type("query");
+ expect(onQuery.mock.calls).toEqual([["query"]]);
+ await changeSearchMode(host, "content");
+ expect(onPending.mock.calls).toEqual([[true]]);
+ await type("queries");
+ await changeSearchMode(host, "name");
+ expect(onQuery.mock.calls).toEqual([["query"], ["queries"]]);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(onQuery).toHaveBeenCalledTimes(2);
+ expect(onPending.mock.calls).toEqual([[true], [false]]);
+ });
+
+ it("clears immediately and never submits a delayed query after unmount", async () => {
+ const { host, type, onQuery } = await mountSearch();
+ await type("select");
+ host.querySelector<HTMLButtonElement>("button")!.click();
+ expect(onQuery.mock.calls.every(([query]) => query === "")).toBe(true);
+ await type("other");
+ const { app } = mounted.pop()!;
+ app.unmount();
+ host.remove();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(onQuery.mock.calls.every(([query]) => query === "")).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/components/layout/__tests__/sqlSearchTestUtils.ts b/apps/desktop/src/components/layout/__tests__/sqlSearchTestUtils.ts
new file mode 100644
index 0000000000..49a3cc501c
--- /dev/null
+++ b/apps/desktop/src/components/layout/__tests__/sqlSearchTestUtils.ts
@@ -0,0 +1,41 @@
+import { defineComponent, h, nextTick } from "vue";
+
+// Keep the scope's v-model contract while avoiding portal/pointer behavior in panel tests.
+export const Select = defineComponent({
+ props: { modelValue: String },
+ emits: ["update:modelValue"],
+ setup(props, { emit, slots }) {
+ return () =>
+ h(
+ "select",
+ {
+ "data-search-mode": "true",
+ value: props.modelValue,
+ onChange: (event: Event) => emit("update:modelValue", (event.target as HTMLSelectElement).value),
+ },
+ slots.default?.(),
+ );
+ },
+});
+export const SelectContent = defineComponent({
+ setup:
+ (_, { slots }) =>
+ () =>
+ slots.default?.(),
+});
+export const SelectItem = defineComponent({
+ props: { value: String },
+ setup:
+ (props, { slots }) =>
+ () =>
+ h("option", { value: props.value }, slots.default?.()),
+});
+export const SelectTrigger = defineComponent({ setup: () => () => null });
+export const SelectValue = SelectTrigger;
+
+export async function changeSearchMode(host: HTMLElement, mode: "name" | "content") {
+ const select = host.querySelector<HTMLSelectElement>("[data-search-mode]")!;
+ select.value = mode;
+ select.dispatchEvent(new Event("change"));
+ await nextTick();
+}
diff --git a/apps/desktop/src/composables/useSqlFileContentSearch.ts b/apps/desktop/src/composables/useSqlFileContentSearch.ts
new file mode 100644
index 0000000000..a68ac1cdec
--- /dev/null
+++ b/apps/desktop/src/composables/useSqlFileContentSearch.ts
@@ -0,0 +1,93 @@
+import { computed, onBeforeUnmount, ref, shallowRef, watch } from "vue";
+import type { SqlFileContentMatch, SqlFileEntry } from "@/lib/backend/api";
+import { contentMatchPathSet, searchSqlFileContents, type SqlFileContentSearchResult } from "@/lib/sql/sqlFileContentSearch";
+import { getSqlFileFilter } from "@/lib/sqlFile/sqlFileFolders";
+
+interface SearchFolder {
+ path: string;
+ entries: SqlFileEntry[];
+ loading: boolean;
+ refreshing: boolean;
+}
+
+interface SearchRequest {
+ generation: number;
+ roots: string[];
+ query: string;
+ fileFilter: string;
+}
+
+/** Keep disk reads off the render path and serialize scans while typing. */
+export function useSqlFileContentSearch(getQuery: () => string, getFolders: () => SearchFolder[], getInputPending: () => boolean = () => false) {
+ const result = shallowRef<SqlFileContentSearchResult | null>(null);
+ const searching = ref(false);
+ const error = ref("");
+ let generation = 0;
+ let disposed = false;
+ let running = false;
+ let pending: SearchRequest | null = null;
+ let resultQuery = "";
+ let resultFileFilter = "";
+
+ async function runPending() {
+ if (disposed || running || !pending) return;
+ const request = pending;
+ pending = null;
+ running = true;
+ try {
+ const response = await searchSqlFileContents(request);
+ if (!disposed && request.generation === generation) {
+ resultQuery = request.query;
+ resultFileFilter = request.fileFilter;
+ result.value = response;
+ }
+ } catch (cause) {
+ if (!disposed && request.generation === generation) error.value = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ running = false;
+ if (!disposed && request.generation === generation) searching.value = false;
+ // Only the latest committed request survives a slow filesystem scan.
+ void runPending();
+ }
+ }
+
+ watch(
+ () => ({
+ query: getQuery(),
+ inputPending: getInputPending(),
+ // Track entry replacement and refresh state, not expansion/selection.
+ folders: getFolders().map((folder) => ({ path: folder.path, entries: folder.entries, loading: folder.loading, refreshing: folder.refreshing })),
+ }),
+ ({ query, folders, inputPending }) => {
+ const current = ++generation;
+ pending = null;
+ const fileFilter = getSqlFileFilter();
+ // Refresh in place: removing content-only hits while rescanning shrinks
+ // the scroll container and destroys its rows and expanded snippets.
+ // A different query/filter must never display the previous search's hits.
+ if (!query || query !== resultQuery || fileFilter !== resultFileFilter || folders.length === 0) result.value = null;
+ error.value = "";
+ searching.value = !inputPending && !!query && folders.length > 0;
+ if (!searching.value || folders.some((folder) => folder.loading || folder.refreshing)) return;
+
+ pending = { generation: current, roots: folders.map((folder) => folder.path), query, fileFilter };
+ void runPending();
+ },
+ { immediate: true, flush: "sync" },
+ );
+
+ onBeforeUnmount(() => {
+ disposed = true;
+ generation++;
+ pending = null;
+ });
+
+ const matchesByPath = computed(() => result.value?.matchesByPath ?? new Map<string, SqlFileContentMatch>());
+ const matchingPaths = computed(() => contentMatchPathSet(result.value));
+ const incomplete = computed(() => !!result.value && (result.value.truncated || result.value.skippedFiles.length > 0));
+ const skippedCount = computed(() => result.value?.skippedFiles.length ?? 0);
+ const skippedFiles = computed(() => result.value?.skippedFiles ?? []);
+ const truncated = computed(() => result.value?.truncated ?? false);
+
+ return { searching, error, matchesByPath, matchingPaths, incomplete, skippedCount, skippedFiles, truncated };
+}
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index a1c6b38bd2..4ad5640d1e 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -604,6 +604,8 @@ export default withEnglishFallback({
collapseAll: "Hamısını yığ",
moreMatches: "+ {count} uyğunluq daha",
collapseMatches: "Yığ",
+ searchContentIncomplete: "Axtarış nəticələri natamamdır: {count} faylın məzmunu yüklənə bilmədi.",
+ matchPreviewLimit: "Cəmi {total} uyğun sətirdən yalnız ilk {limit} sətir üçün önizləmə mövcuddur.",
},
connection: {
@@ -6899,6 +6901,22 @@ export default withEnglishFallback({
completedWithErrors: "İcra tamamlandı: {succeeded} uğurlu, {failed} uğursuz",
},
sqlFileTree: {
+ searchIncompleteHelp: "Bu axtarışın natamam olmasının səbəbləri:",
+ searchSkippedTooLarge: "32 MiB-dan böyükdür: {count} fayl ötürüldü.",
+ searchSkippedUnreadable: "Oxumaq mümkün olmadı (silinmiş ola bilər və ya giriş icazəsi yoxdur): {count} fayl və ya qovluq.",
+ searchSkippedInvalidEncoding: "Fayl kodlaşdırması tanınmadı: {count} fayl.",
+ searchSkippedOutsideRoot: "Həqiqi yol seçilmiş kök qovluqdan kənardadır: {count} fayl.",
+ searchSkippedNotRegularFile: "Adi fayl deyil (məsələn, simvolik keçidlə əvəz edilib): {count} element.",
+ searchSkippedOther: "Digər səbəblərlə ötürüldü: {count} element.",
+ searchPreviewLimits: "Önizləmələr qısaldılıb: hər fayl üçün ən çox {perFile}, hər axtarış üçün {total} sətir. Uyğun faylların axtarışı və uyğun sətirlərin sayılması davam edir.",
+ searchMode: "Axtarış sahəsi",
+ searchByName: "Fayl",
+ searchByContent: "Məzmun",
+ searchContentPlaceholder: "Fayl məzmununda axtar...",
+ searchPlaceholder: "Fayl adlarında axtar...",
+ searching: "Fayl məzmununda axtarılır...",
+ searchIncomplete: "Axtarış natamamdır: {skipped} fayl və ya qovluq ötürüldü; uyğun fraqmentlər qısaldıla bilər.",
+ searchFailed: "Məzmun axtarışı uğursuz oldu: {message}",
sortManual: "Əl ilə sıralama",
sortManualHint: "Sıralamaq üçün eyni qovluqdakı faylları sürükləyin. Axtarış zamanı sürükləmə deaktivdir.",
sortSaveFailed: "Fayl sıralama seçimini saxlamaq mümkün olmadı.",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index b54c37ae47..002d7357d6 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1239,6 +1239,8 @@ export default {
collapseAll: "Collapse all",
moreMatches: "+ {count} more matches",
collapseMatches: "Collapse",
+ searchContentIncomplete: "Search results are incomplete: content could not be loaded for {count} files.",
+ matchPreviewLimit: "Previews are limited to the first {limit} of {total} matching lines.",
},
connection: {
@@ -8719,6 +8721,22 @@ export default {
completedWithErrors: "Execution completed: {succeeded} succeeded, {failed} failed",
},
sqlFileTree: {
+ searchIncompleteHelp: "Why this search is incomplete:",
+ searchSkippedTooLarge: "Larger than 32 MiB: {count} file(s) skipped.",
+ searchSkippedUnreadable: "Could not read (possibly removed or access denied): {count} file(s) or folder(s).",
+ searchSkippedInvalidEncoding: "Unrecognized file encoding: {count} file(s).",
+ searchSkippedOutsideRoot: "Resolved path outside the selected root folder: {count} file(s).",
+ searchSkippedNotRegularFile: "Not a regular file (for example, replaced by a symbolic link): {count} item(s).",
+ searchSkippedOther: "Skipped for other reasons: {count} item(s).",
+ searchPreviewLimits: "Matching previews were truncated: up to {perFile} lines per file and {total} lines per search. Matching files and line counts are still collected.",
+ searchMode: "Search scope",
+ searchByName: "File",
+ searchByContent: "Content",
+ searchContentPlaceholder: "Search file contents...",
+ searchPlaceholder: "Search file names...",
+ searching: "Searching file contents...",
+ searchIncomplete: "Search incomplete: {skipped} file(s) or folder(s) skipped; matching snippets may be truncated.",
+ searchFailed: "Content search failed: {message}",
sortManual: "Manual order",
sortManualHint: "Drag files within the same folder to reorder. Dragging is disabled while searching.",
sortSaveFailed: "Could not save the file sorting preference.",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 16ce71600d..8a6b8eb918 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1089,6 +1089,8 @@ export default withEnglishFallback({
collapseAll: "Contraer todo",
moreMatches: "+ {count} coincidencias más",
collapseMatches: "Contraer",
+ searchContentIncomplete: "Resultados incompletos: no se pudo cargar el contenido de {count} archivos.",
+ matchPreviewLimit: "Las vistas previas se limitan a las primeras {limit} de {total} líneas coincidentes.",
},
connection: {
@@ -10622,6 +10624,22 @@ export default withEnglishFallback({
actionSuccess: '{action} completado para "{name}".',
},
sqlFileTree: {
+ searchIncompleteHelp: "Por qué esta búsqueda está incompleta:",
+ searchSkippedTooLarge: "Más de 32 MiB: {count} archivos omitidos.",
+ searchSkippedUnreadable: "No se pudieron leer (quizá eliminados o sin permiso): {count} archivos o carpetas.",
+ searchSkippedInvalidEncoding: "Codificación no reconocida: {count} archivos.",
+ searchSkippedOutsideRoot: "Ruta real fuera de la carpeta raíz seleccionada: {count} archivos.",
+ searchSkippedNotRegularFile: "No son archivos normales (por ejemplo, sustituidos por enlaces simbólicos): {count} elementos.",
+ searchSkippedOther: "Omitidos por otros motivos: {count} elementos.",
+ searchPreviewLimits: "Vistas previas truncadas: hasta {perFile} líneas por archivo y {total} por búsqueda. Se siguen recopilando archivos coincidentes y contando líneas.",
+ searchMode: "Ámbito de búsqueda",
+ searchByName: "Archivo",
+ searchByContent: "Contenido",
+ searchContentPlaceholder: "Buscar en el contenido...",
+ searchPlaceholder: "Buscar nombres de archivos...",
+ searching: "Buscando en el contenido de archivos...",
+ searchIncomplete: "Búsqueda incompleta: se omitieron {skipped} archivos o carpetas; los fragmentos coincidentes pueden estar truncados.",
+ searchFailed: "Error al buscar en el contenido: {message}",
sortManual: "Orden manual",
sortManualHint: "Arrastra archivos dentro de la misma carpeta para reordenarlos. No se puede arrastrar durante la búsqueda.",
sortSaveFailed: "No se pudo guardar la preferencia de orden de los archivos.",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index b1072a0683..821dea4cfe 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -748,6 +748,8 @@ export default withEnglishFallback({
createFolderFailed: "Gagal membuat folder: {message}",
},
sqlLibrary: {
+ searchContentIncomplete: "Hasil pencarian tidak lengkap: konten {count} berkas tidak dapat dimuat.",
+ matchPreviewLimit: "Pratinjau dibatasi pada {limit} baris pertama dari {total} baris yang cocok.",
title: "SQL Library",
storageHelp: "Konten SQL Library disimpan di data aplikasi DBX, bukan sebagai file .sql tersendiri di disk.\nUntuk menggunakan file di sistem berkas, ekspor SQL Library.",
unassociated: "Tidak terkait",
@@ -7600,6 +7602,22 @@ export default withEnglishFallback({
completedWithErrors: "Eksekusi selesai: {succeeded} berhasil, {failed} gagal",
},
sqlFileTree: {
+ searchIncompleteHelp: "Alasan hasil pencarian ini tidak lengkap:",
+ searchSkippedTooLarge: "Lebih besar dari 32 MiB: {count} file dilewati.",
+ searchSkippedUnreadable: "Tidak dapat dibaca (mungkin dihapus atau akses ditolak): {count} file atau folder.",
+ searchSkippedInvalidEncoding: "Pengodean file tidak dikenali: {count} file.",
+ searchSkippedOutsideRoot: "Jalur sebenarnya di luar folder akar yang dipilih: {count} file.",
+ searchSkippedNotRegularFile: "Bukan file biasa (misalnya diganti tautan simbolis): {count} item.",
+ searchSkippedOther: "Dilewati karena alasan lain: {count} item.",
+ searchPreviewLimits: "Pratinjau dipotong: maksimal {perFile} baris per file dan {total} baris per pencarian. Pencarian file yang cocok dan penghitungan baris tetap dilanjutkan.",
+ searchMode: "Lingkup pencarian",
+ searchByName: "Berkas",
+ searchByContent: "Isi",
+ searchContentPlaceholder: "Cari isi file...",
+ searchPlaceholder: "Cari nama file...",
+ searching: "Mencari isi file...",
+ searchIncomplete: "Pencarian tidak lengkap: {skipped} file atau folder dilewati; cuplikan yang cocok mungkin terpotong.",
+ searchFailed: "Pencarian isi gagal: {message}",
sortManual: "Urutan manual",
sortManualHint: "Seret file dalam folder yang sama untuk mengubah urutan. Penyeretan dinonaktifkan saat mencari.",
sortSaveFailed: "Tidak dapat menyimpan preferensi urutan file.",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 3288e53908..26c5f9d57a 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1078,6 +1078,8 @@ export default withEnglishFallback({
collapseAll: "Comprimi tutto",
moreMatches: "+ altre {count} corrispondenze",
collapseMatches: "Comprimi",
+ searchContentIncomplete: "Risultati incompleti: impossibile caricare il contenuto di {count} file.",
+ matchPreviewLimit: "Le anteprime sono limitate alle prime {limit} righe su {total} righe corrispondenti.",
},
connection: {
@@ -10370,6 +10372,22 @@ export default withEnglishFallback({
actionSuccess: '{action} completato per "{name}".',
},
sqlFileTree: {
+ searchIncompleteHelp: "Perché questa ricerca è incompleta:",
+ searchSkippedTooLarge: "Oltre 32 MiB: {count} file ignorati.",
+ searchSkippedUnreadable: "Lettura non riuscita (forse rimossi o senza permessi): {count} file o cartelle.",
+ searchSkippedInvalidEncoding: "Codifica non riconosciuta: {count} file.",
+ searchSkippedOutsideRoot: "Percorso effettivo fuori dalla cartella radice selezionata: {count} file.",
+ searchSkippedNotRegularFile: "Non sono file regolari (ad esempio, sostituiti da collegamenti simbolici): {count} elementi.",
+ searchSkippedOther: "Ignorati per altri motivi: {count} elementi.",
+ searchPreviewLimits: "Anteprime troncate: fino a {perFile} righe per file e {total} per ricerca. La ricerca dei file corrispondenti e il conteggio delle righe continuano.",
+ searchMode: "Ambito di ricerca",
+ searchByName: "File",
+ searchByContent: "Contenuto",
+ searchContentPlaceholder: "Cerca nei contenuti dei file...",
+ searchPlaceholder: "Cerca nomi di file...",
+ searching: "Ricerca nei contenuti dei file...",
+ searchIncomplete: "Ricerca incompleta: {skipped} file o cartelle ignorati; i frammenti corrispondenti potrebbero essere troncati.",
+ searchFailed: "Ricerca nei contenuti non riuscita: {message}",
sortManual: "Ordine manuale",
sortManualHint: "Trascina i file nella stessa cartella per riordinarli. Il trascinamento è disabilitato durante la ricerca.",
sortSaveFailed: "Impossibile salvare la preferenza di ordinamento dei file.",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index fe8012ecc2..4a8c23f17e 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1079,6 +1079,8 @@ export default withEnglishFallback({
collapseAll: "すべて折りたたむ",
moreMatches: "+ 他 {count} 件の一致",
collapseMatches: "折りたたむ",
+ searchContentIncomplete: "検索結果は不完全です:{count} 件のファイルの内容を読み込めませんでした。",
+ matchPreviewLimit: "一致する全 {total} 行のうち、先頭 {limit} 行のみプレビューできます。",
},
connection: {
title: "新しい接続",
@@ -10406,6 +10408,22 @@ export default withEnglishFallback({
actionSuccess: "「{name}」の{action}が完了しました。",
},
sqlFileTree: {
+ searchIncompleteHelp: "今回の検索結果が不完全な理由:",
+ searchSkippedTooLarge: "32 MiB を超えるためスキップ:{count} ファイル。",
+ searchSkippedUnreadable: "読み取り不可(削除済み、またはアクセス権限がない可能性):{count} ファイルまたはフォルダー。",
+ searchSkippedInvalidEncoding: "文字コードを認識できません:{count} ファイル。",
+ searchSkippedOutsideRoot: "実際のパスが選択したルートフォルダーの外にあります:{count} ファイル。",
+ searchSkippedNotRegularFile: "通常のファイルではありません(シンボリックリンクへの置き換えなど):{count} 項目。",
+ searchSkippedOther: "その他の理由でスキップ:{count} 項目。",
+ searchPreviewLimits: "一致行のプレビューは省略されています。上限はファイルごとに {perFile} 行、検索ごとに {total} 行です。一致ファイルの検索と一致行数の集計は継続します。",
+ searchMode: "検索対象",
+ searchByName: "ファイル",
+ searchByContent: "内容",
+ searchContentPlaceholder: "ファイル内容を検索...",
+ searchPlaceholder: "ファイル名を検索...",
+ searching: "ファイルの内容を検索中...",
+ searchIncomplete: "検索結果は不完全です:{skipped} 個のファイルまたはフォルダーをスキップしました。一致したスニペットは省略されている場合があります。",
+ searchFailed: "内容の検索に失敗しました:{message}",
sortManual: "手動並べ替え",
sortManualHint: "同じフォルダー内のファイルをドラッグして並べ替えます。検索中はドラッグできません。",
sortSaveFailed: "ファイルの並べ替え設定を保存できませんでした。",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 0be76c2cba..3865a0f1cd 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -1085,6 +1085,8 @@ export default withEnglishFallback({
collapseAll: "모두 접기",
moreMatches: "+ {count}개 더 일치",
collapseMatches: "접기",
+ searchContentIncomplete: "검색 결과가 완전하지 않습니다. 파일 {count}개의 내용을 불러오지 못했습니다.",
+ matchPreviewLimit: "일치하는 총 {total}개 줄 중 처음 {limit}개 줄만 미리 볼 수 있습니다.",
},
connection: {
title: "새 연결",
@@ -7523,6 +7525,22 @@ export default withEnglishFallback({
completedWithErrors: "실행 완료: 성공 {succeeded}개, 실패 {failed}개",
},
sqlFileTree: {
+ searchIncompleteHelp: "이번 검색 결과가 완전하지 않은 이유:",
+ searchSkippedTooLarge: "32 MiB 초과로 건너뜀: 파일 {count}개.",
+ searchSkippedUnreadable: "읽을 수 없음(삭제되었거나 접근 권한이 없을 수 있음): 파일 또는 폴더 {count}개.",
+ searchSkippedInvalidEncoding: "파일 인코딩을 인식할 수 없음: 파일 {count}개.",
+ searchSkippedOutsideRoot: "실제 경로가 선택한 루트 폴더 밖에 있음: 파일 {count}개.",
+ searchSkippedNotRegularFile: "일반 파일이 아님(예: 심볼릭 링크로 교체됨): 항목 {count}개.",
+ searchSkippedOther: "기타 이유로 건너뜀: 항목 {count}개.",
+ searchPreviewLimits: "미리보기가 잘렸습니다. 파일당 최대 {perFile}줄, 검색당 최대 {total}줄입니다. 일치하는 파일 검색과 일치 줄 수 집계는 계속됩니다.",
+ searchMode: "검색 범위",
+ searchByName: "파일",
+ searchByContent: "내용",
+ searchContentPlaceholder: "파일 내용 검색...",
+ searchPlaceholder: "파일 이름 검색...",
+ searching: "파일 내용을 검색하는 중...",
+ searchIncomplete: "검색이 완전하지 않습니다: 파일 또는 폴더 {skipped}개를 건너뛰었으며 일치하는 코드 조각이 잘렸을 수 있습니다.",
+ searchFailed: "내용 검색 실패: {message}",
sortManual: "수동 정렬",
sortManualHint: "같은 폴더의 파일을 드래그하여 순서를 변경합니다. 검색 중에는 드래그할 수 없습니다.",
sortSaveFailed: "파일 정렬 설정을 저장할 수 없습니다.",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index b0629b4a6e..2b2f1dc0e4 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -872,6 +872,8 @@ export default withEnglishFallback({
collapseAll: "Zwiń wszystko",
moreMatches: "+ {count} dodatkowych wyników",
collapseMatches: "Zwiń",
+ searchContentIncomplete: "Niepełne wyniki wyszukiwania: nie udało się wczytać treści {count} plików.",
+ matchPreviewLimit: "Podgląd jest ograniczony do pierwszych {limit} z {total} pasujących wierszy.",
},
connection: {
@@ -7654,6 +7656,22 @@ export default withEnglishFallback({
totalFiles: "Pliki: {count}",
},
sqlFileTree: {
+ searchIncompleteHelp: "Dlaczego wyniki wyszukiwania są niepełne:",
+ searchSkippedTooLarge: "Rozmiar ponad 32 MiB: pominięto {count} plików.",
+ searchSkippedUnreadable: "Nie można odczytać (być może usunięte lub brak dostępu): {count} plików lub folderów.",
+ searchSkippedInvalidEncoding: "Nierozpoznane kodowanie: {count} plików.",
+ searchSkippedOutsideRoot: "Rzeczywista ścieżka poza wybranym folderem głównym: {count} plików.",
+ searchSkippedNotRegularFile: "Nie są zwykłymi plikami (np. zastąpione dowiązaniami symbolicznymi): {count} elementów.",
+ searchSkippedOther: "Pominięto z innych powodów: {count} elementów.",
+ searchPreviewLimits: "Podgląd został skrócony: do {perFile} wierszy na plik i {total} na wyszukiwanie. Wyszukiwanie pasujących plików i zliczanie wierszy trwa nadal.",
+ searchMode: "Zakres wyszukiwania",
+ searchByName: "Plik",
+ searchByContent: "Treść",
+ searchContentPlaceholder: "Szukaj w treści plików...",
+ searchPlaceholder: "Szukaj nazw plików...",
+ searching: "Wyszukiwanie w treści plików...",
+ searchIncomplete: "Wyszukiwanie niepełne: pominięto {skipped} plików lub folderów; pasujące fragmenty mogą być ucięte.",
+ searchFailed: "Wyszukiwanie w treści nie powiodło się: {message}",
sortManual: "Kolejność ręczna",
sortManualHint: "Przeciągaj pliki w tym samym folderze, aby zmienić kolejność. Przeciąganie jest wyłączone podczas wyszukiwania.",
sortSaveFailed: "Nie udało się zapisać ustawienia sortowania plików.",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 5b373b5426..fdab04a127 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1079,6 +1079,8 @@ export default withEnglishFallback({
collapseAll: "Recolher todos",
moreMatches: "+ {count} mais correspondências",
collapseMatches: "Recolher",
+ searchContentIncomplete: "Resultados incompletos: não foi possível carregar o conteúdo de {count} arquivos.",
+ matchPreviewLimit: "As prévias são limitadas às primeiras {limit} de {total} linhas correspondentes.",
},
connection: {
@@ -10366,6 +10368,22 @@ export default withEnglishFallback({
actionSuccess: '{action} concluído para "{name}".',
},
sqlFileTree: {
+ searchIncompleteHelp: "Por que esta pesquisa está incompleta:",
+ searchSkippedTooLarge: "Maiores que 32 MiB: {count} arquivos ignorados.",
+ searchSkippedUnreadable: "Não foi possível ler (talvez removidos ou sem permissão): {count} arquivos ou pastas.",
+ searchSkippedInvalidEncoding: "Codificação não reconhecida: {count} arquivos.",
+ searchSkippedOutsideRoot: "Caminho real fora da pasta raiz selecionada: {count} arquivos.",
+ searchSkippedNotRegularFile: "Não são arquivos comuns (por exemplo, substituídos por links simbólicos): {count} itens.",
+ searchSkippedOther: "Ignorados por outros motivos: {count} itens.",
+ searchPreviewLimits: "Prévias truncadas: até {perFile} linhas por arquivo e {total} por pesquisa. A busca de arquivos correspondentes e a contagem de linhas continuam.",
+ searchMode: "Escopo da pesquisa",
+ searchByName: "Arquivo",
+ searchByContent: "Conteúdo",
+ searchContentPlaceholder: "Pesquisar conteúdo dos arquivos...",
+ searchPlaceholder: "Pesquisar nomes de arquivos...",
+ searching: "Pesquisando conteúdos de arquivos...",
+ searchIncomplete: "Pesquisa incompleta: {skipped} arquivos ou pastas ignorados; os trechos correspondentes podem estar truncados.",
+ searchFailed: "Falha na pesquisa de conteúdo: {message}",
sortManual: "Ordem manual",
sortManualHint: "Arraste arquivos na mesma pasta para reordenar. Não é possível arrastar durante a pesquisa.",
sortSaveFailed: "Não foi possível salvar a preferência de ordenação dos arquivos.",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 5aa2eefb6f..29d7a9fb75 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -1059,6 +1059,8 @@ export default withEnglishFallback({
collapseAll: "Свернуть все",
moreMatches: "+ ещё {count} совпадений",
collapseMatches: "Свернуть",
+ searchContentIncomplete: "Результаты поиска неполные: не удалось загрузить содержимое {count} файлов.",
+ matchPreviewLimit: "Предпросмотр ограничен первыми {limit} из {total} совпадающих строк.",
},
connection: {
title: "Новое подключение",
@@ -8965,6 +8967,22 @@ export default withEnglishFallback({
completedWithErrors: "Выполнение завершено: успешно {succeeded}, с ошибкой {failed}",
},
sqlFileTree: {
+ searchIncompleteHelp: "Почему результаты поиска неполные:",
+ searchSkippedTooLarge: "Размер больше 32 MiB: пропущено файлов — {count}.",
+ searchSkippedUnreadable: "Не удалось прочитать (возможно, удалены или нет доступа): файлов или папок — {count}.",
+ searchSkippedInvalidEncoding: "Неизвестная кодировка: файлов — {count}.",
+ searchSkippedOutsideRoot: "Фактический путь вне выбранной корневой папки: файлов — {count}.",
+ searchSkippedNotRegularFile: "Не являются обычными файлами (например, заменены символическими ссылками): объектов — {count}.",
+ searchSkippedOther: "Пропущено по другим причинам: объектов — {count}.",
+ searchPreviewLimits: "Предпросмотр сокращён: до {perFile} строк на файл и {total} строк на поиск. Поиск подходящих файлов и подсчёт совпадающих строк продолжаются.",
+ searchMode: "Область поиска",
+ searchByName: "Файл",
+ searchByContent: "Содержимое",
+ searchContentPlaceholder: "Поиск по содержимому файлов...",
+ searchPlaceholder: "Поиск по именам файлов...",
+ searching: "Поиск в содержимом файлов...",
+ searchIncomplete: "Поиск неполный: пропущено файлов или папок — {skipped}; совпадающие фрагменты могут быть обрезаны.",
+ searchFailed: "Ошибка поиска по содержимому: {message}",
sortManual: "Ручной порядок",
sortManualHint: "Перетаскивайте файлы в одной папке для изменения порядка. Во время поиска перетаскивание отключено.",
sortSaveFailed: "Не удалось сохранить настройку сортировки файлов.",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 1b186d29c5..155c608687 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -1169,6 +1169,8 @@ export default withEnglishFallback({
collapseAll: "ยุบทั้งหมด",
moreMatches: "+ อีก {count} รายการที่ตรงกัน",
collapseMatches: "ยุบ",
+ searchContentIncomplete: "ผลการค้นหาไม่ครบถ้วน: ไม่สามารถโหลดเนื้อหาของไฟล์ {count} ไฟล์ได้",
+ matchPreviewLimit: "แสดงตัวอย่างได้เฉพาะ {limit} บรรทัดแรกจากทั้งหมด {total} บรรทัดที่ตรงกัน",
},
connection: {
title: "การเชื่อมต่อใหม่",
@@ -9325,6 +9327,22 @@ export default withEnglishFallback({
completedWithErrors: "การเรียกใช้เสร็จสิ้น: สำเร็จ {succeeded}, ล้มเหลว {failed}",
},
sqlFileTree: {
+ searchIncompleteHelp: "เหตุผลที่ผลการค้นหาครั้งนี้ไม่ครบถ้วน:",
+ searchSkippedTooLarge: "ขนาดเกิน 32 MiB: ข้าม {count} ไฟล์",
+ searchSkippedUnreadable: "อ่านไม่ได้ (อาจถูกลบหรือไม่มีสิทธิ์เข้าถึง): {count} ไฟล์หรือโฟลเดอร์",
+ searchSkippedInvalidEncoding: "ไม่รู้จักการเข้ารหัสไฟล์: {count} ไฟล์",
+ searchSkippedOutsideRoot: "เส้นทางจริงอยู่นอกโฟลเดอร์รากที่เลือก: {count} ไฟล์",
+ searchSkippedNotRegularFile: "ไม่ใช่ไฟล์ปกติ (เช่น ถูกแทนที่ด้วยลิงก์สัญลักษณ์): {count} รายการ",
+ searchSkippedOther: "ข้ามด้วยเหตุผลอื่น: {count} รายการ",
+ searchPreviewLimits: "ตัวอย่างถูกตัดทอน: สูงสุด {perFile} บรรทัดต่อไฟล์ และ {total} บรรทัดต่อการค้นหา แต่ยังคงค้นหาไฟล์ที่ตรงกันและนับจำนวนบรรทัดที่ตรงกันต่อไป",
+ searchMode: "ขอบเขตการค้นหา",
+ searchByName: "ไฟล์",
+ searchByContent: "เนื้อหา",
+ searchContentPlaceholder: "ค้นหาเนื้อหาไฟล์...",
+ searchPlaceholder: "ค้นหาชื่อไฟล์...",
+ searching: "กำลังค้นหาเนื้อหาไฟล์...",
+ searchIncomplete: "ผลการค้นหาไม่ครบถ้วน: ข้ามไฟล์หรือโฟลเดอร์ {skipped} รายการ และส่วนที่ตรงกันอาจถูกตัดทอน",
+ searchFailed: "ค้นหาเนื้อหาไม่สำเร็จ: {message}",
sortManual: "เรียงลำดับด้วยตนเอง",
sortManualHint: "ลากไฟล์ในโฟลเดอร์เดียวกันเพื่อจัดลำดับใหม่ ไม่สามารถลากขณะค้นหาได้",
sortSaveFailed: "ไม่สามารถบันทึกการตั้งค่าการเรียงลำดับไฟล์ได้",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 0174df292b..8e97e35660 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -604,6 +604,8 @@ export default withEnglishFallback({
collapseAll: "Tümünü daralt",
moreMatches: "+ {count} eşleşme daha",
collapseMatches: "Daralt",
+ searchContentIncomplete: "Arama sonuçları eksik: {count} dosyanın içeriği yüklenemedi.",
+ matchPreviewLimit: "Önizlemeler, eşleşen {total} satırın ilk {limit} satırıyla sınırlıdır.",
},
connection: {
@@ -6779,6 +6781,22 @@ export default withEnglishFallback({
completedWithErrors: "Çalıştırma tamamlandı: {succeeded} başarılı, {failed} başarısız",
},
sqlFileTree: {
+ searchIncompleteHelp: "Bu aramanın eksik olmasının nedenleri:",
+ searchSkippedTooLarge: "32 MiB üzeri: {count} dosya atlandı.",
+ searchSkippedUnreadable: "Okunamadı (silinmiş olabilir veya erişim izni yok): {count} dosya veya klasör.",
+ searchSkippedInvalidEncoding: "Dosya kodlaması tanınmadı: {count} dosya.",
+ searchSkippedOutsideRoot: "Gerçek yol seçilen kök klasörün dışında: {count} dosya.",
+ searchSkippedNotRegularFile: "Normal dosya değil (örneğin sembolik bağlantıyla değiştirilmiş): {count} öğe.",
+ searchSkippedOther: "Diğer nedenlerle atlandı: {count} öğe.",
+ searchPreviewLimits: "Önizlemeler kısaltıldı: dosya başına en fazla {perFile}, arama başına {total} satır. Eşleşen dosyaların aranması ve satırların sayılması devam eder.",
+ searchMode: "Arama kapsamı",
+ searchByName: "Dosya",
+ searchByContent: "İçerik",
+ searchContentPlaceholder: "Dosya içeriklerinde ara...",
+ searchPlaceholder: "Dosya adlarında ara...",
+ searching: "Dosya içerikleri aranıyor...",
+ searchIncomplete: "Arama eksik: {skipped} dosya veya klasör atlandı; eşleşen parçacıklar kısaltılmış olabilir.",
+ searchFailed: "İçerik araması başarısız: {message}",
sortManual: "Elle sıralama",
sortManualHint: "Sıralamayı değiştirmek için aynı klasördeki dosyaları sürükleyin. Arama sırasında sürükleme devre dışıdır.",
sortSaveFailed: "Dosya sıralama tercihi kaydedilemedi.",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 70b2e5623f..0766543113 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1175,6 +1175,8 @@ export default withEnglishFallback({
collapseAll: "全部折叠",
moreMatches: "+ {count} 项更多匹配",
collapseMatches: "收起",
+ searchContentIncomplete: "搜索结果不完整:{count} 个文件的内容未能加载。",
+ matchPreviewLimit: "共 {total} 行匹配,仅提供前 {limit} 行的预览。",
},
connection: {
@@ -8687,6 +8689,22 @@ export default withEnglishFallback({
completedWithErrors: "执行完成:成功 {succeeded} 条,失败 {failed} 条",
},
sqlFileTree: {
+ searchIncompleteHelp: "本次搜索结果不完整的原因:",
+ searchSkippedTooLarge: "超过 32 MiB,已跳过:{count} 个文件。",
+ searchSkippedUnreadable: "无法读取(可能已删除或无访问权限):{count} 个文件或目录。",
+ searchSkippedInvalidEncoding: "无法识别文件编码:{count} 个文件。",
+ searchSkippedOutsideRoot: "实际路径不在所选根目录内:{count} 个文件。",
+ searchSkippedNotRegularFile: "不是普通文件(例如已变为符号链接):{count} 项。",
+ searchSkippedOther: "其他原因跳过:{count} 项。",
+ searchPreviewLimits: "匹配预览已截断:每个文件最多 {perFile} 行,每次搜索最多 {total} 行;仍会继续查找匹配文件并统计匹配行数。",
+ searchMode: "搜索范围",
+ searchByName: "文件",
+ searchByContent: "内容",
+ searchContentPlaceholder: "搜索文件内容...",
+ searchPlaceholder: "搜索文件名...",
+ searching: "正在搜索文件内容...",
+ searchIncomplete: "搜索结果不完整:已跳过 {skipped} 个文件或目录,匹配片段可能被截断。",
+ searchFailed: "内容搜索失败:{message}",
sortManual: "手动排序",
sortManualHint: "拖拽同一目录中的文件调整顺序;搜索期间不可拖拽。",
sortSaveFailed: "无法保存文件排序偏好。",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 2681bfd0b2..5507142c9c 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1083,6 +1083,8 @@ export default withEnglishFallback({
collapseAll: "全部摺疊",
moreMatches: "+ {count} 項更多相符",
collapseMatches: "收起",
+ searchContentIncomplete: "搜尋結果不完整:{count} 個檔案的內容無法載入。",
+ matchPreviewLimit: "共 {total} 行相符,僅提供前 {limit} 行的預覽。",
},
connection: {
@@ -10376,6 +10378,22 @@ export default withEnglishFallback({
actionSuccess: "已完成對「{name}」的{action}。",
},
sqlFileTree: {
+ searchIncompleteHelp: "本次搜尋結果不完整的原因:",
+ searchSkippedTooLarge: "超過 32 MiB,已略過:{count} 個檔案。",
+ searchSkippedUnreadable: "無法讀取(可能已刪除或無存取權限):{count} 個檔案或目錄。",
+ searchSkippedInvalidEncoding: "無法識別檔案編碼:{count} 個檔案。",
+ searchSkippedOutsideRoot: "實際路徑不在所選根目錄內:{count} 個檔案。",
+ searchSkippedNotRegularFile: "不是一般檔案(例如已變為符號連結):{count} 項。",
+ searchSkippedOther: "因其他原因略過:{count} 項。",
+ searchPreviewLimits: "相符預覽已截斷:每個檔案最多 {perFile} 行,每次搜尋最多 {total} 行;仍會繼續尋找相符檔案並統計相符行數。",
+ searchMode: "搜尋範圍",
+ searchByName: "檔案",
+ searchByContent: "內容",
+ searchContentPlaceholder: "搜尋檔案內容...",
+ searchPlaceholder: "搜尋檔案名稱...",
+ searching: "正在搜尋檔案內容...",
+ searchIncomplete: "搜尋結果不完整:已略過 {skipped} 個檔案或目錄,相符片段可能已截斷。",
+ searchFailed: "內容搜尋失敗:{message}",
sortManual: "手動排序",
sortManualHint: "拖曳同一目錄中的檔案調整順序;搜尋期間無法拖曳。",
sortSaveFailed: "無法儲存檔案排序偏好。",
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 0f6f128adc..f755999906 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -523,6 +523,7 @@ export const inspectExternalSqlFile = forward("inspectExternalSqlFile");
export const writeExternalSqlFile = forward("writeExternalSqlFile");
export const saveExternalSqlFile = forward("saveExternalSqlFile");
export const listSqlFilesInFolder = forward("listSqlFilesInFolder");
+export const searchSqlFileContents = forward("searchSqlFileContents");
export const globalSearch = forward("globalSearch");
export const loadGlobalSearchSettings = forward("loadGlobalSearchSettings");
export const saveGlobalSearchSettings = forward("saveGlobalSearchSettings");
@@ -1216,6 +1217,8 @@ export type {
QueryResultExportRequest,
AgentEvent,
SqlFileEntry,
+ SqlFileContentMatch,
+ SqlFileContentSearchResult,
GlobalSearchRequest,
GlobalSearchMatch,
GlobalSearchSettings,
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index f4142e51ca..97d5a34b0d 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -3129,6 +3129,10 @@ export async function listSqlFilesInFolder(_folderPath: string, _fileFilter?: st
throw new Error("Listing SQL files in a folder is only available in the desktop app");
}
+export async function searchSqlFileContents(_roots: string[], _query: string, _fileFilter?: string): Promise<import("@/lib/backend/tauri").SqlFileContentSearchResult> {
+ throw new Error("Searching SQL file contents is only available in the desktop app");
+}
+
export async function createSqlFileInFolder(_rootPath: string, _directoryPath: string, _fileName: string): Promise<string> {
throw new Error("Managing SQL files in folders is only available in the desktop app");
}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 8dcf43d541..c587cb3d03 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -1394,6 +1394,20 @@ export async function listSqlFilesInFolder(folderPath: string, fileFilter?: stri
return invoke("list_sql_files_in_folder", { folderPath, fileFilter, includeEmptyDirectories });
}
+export type SqlFileContentMatch = import("@/lib/savedSql/savedSqlSearch").SavedSqlSearchMatchResult & {
+ path: string;
+};
+
+export interface SqlFileContentSearchResult {
+ files: SqlFileContentMatch[];
+ skippedFiles: { path: string; reason: string }[];
+ truncated: boolean;
+}
+
+export async function searchSqlFileContents(roots: string[], query: string, fileFilter?: string): Promise<SqlFileContentSearchResult> {
+ return invoke("search_sql_file_contents", { roots, query, fileFilter });
+}
+
export async function createSqlFileInFolder(rootPath: string, directoryPath: string, fileName: string): Promise<string> {
return invoke("create_sql_file_in_folder", { rootPath, directoryPath, fileName });
}
diff --git a/apps/desktop/src/lib/sql/__tests__/sqlFileContentSearch.spec.ts b/apps/desktop/src/lib/sql/__tests__/sqlFileContentSearch.spec.ts
index fbc3e2ffbf..969df9c4da 100644
--- a/apps/desktop/src/lib/sql/__tests__/sqlFileContentSearch.spec.ts
+++ b/apps/desktop/src/lib/sql/__tests__/sqlFileContentSearch.spec.ts
@@ -1,127 +1,47 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import type { GlobalSearchMatch } from "@/lib/backend/api";
+import type { SqlFileContentSearchResult } 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[]> => []),
+ search: vi.fn(async (_roots: string[], _query: string, _filter: string): Promise<SqlFileContentSearchResult> => ({ files: [], skippedFiles: [], truncated: false })),
}));
+vi.mock("@/lib/backend/api", () => ({ searchSqlFileContents: mocks.search }));
-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,
- };
-}
+import { contentMatchPathSet, searchSqlFileContents } from "../sqlFileContentSearch";
beforeEach(() => {
- mocks.globalSearch.mockReset();
- mocks.globalSearch.mockResolvedValue([]);
+ mocks.search.mockReset();
+ mocks.search.mockResolvedValue({ files: [], skippedFiles: [], truncated: false });
});
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" });
-
+ it("forwards the exact tree filter, including extensionless names", async () => {
+ await searchSqlFileContents({ roots: ["/sql", "/more"], query: " users ", fileFilter: "(?i)(\\.sql$|^README$)" });
+ expect(mocks.search).toHaveBeenCalledWith(["/sql", "/more"], "users", "(?i)(\\.sql$|^README$)");
+ });
+
+ it("skips empty queries and empty roots", async () => {
+ expect((await searchSqlFileContents({ roots: ["/sql"], query: " ", fileFilter: "*.sql" })).matchesByPath.size).toBe(0);
+ expect((await searchSqlFileContents({ roots: [" "], query: "users", fileFilter: "*.sql" })).matchesByPath.size).toBe(0);
+ expect(mocks.search).not.toHaveBeenCalled();
+ });
+
+ it("normalizes paths and preserves hits after the preview budget is exhausted", async () => {
+ const response: SqlFileContentSearchResult = {
+ files: [{ path: "C:\\sql\\a.sql", matches: [], totalMatches: 1200 }],
+ skippedFiles: [{ path: "C:/sql/large.sql", reason: "tooLarge" }],
+ truncated: true,
+ };
+ mocks.search.mockResolvedValue(response);
+ const result = await searchSqlFileContents({ roots: ["C:/sql"], query: "users", fileFilter: "*.sql" });
+ expect(result.matchesByPath.get("C:/sql/a.sql")?.totalMatches).toBe(1200);
+ expect(result.skippedFiles).toEqual(response.skippedFiles);
+ expect(result.truncated).toBe(true);
expect(contentMatchPathSet(result)).toEqual(new Set(["C:/sql/a.sql"]));
expect(contentMatchPathSet(null).size).toBe(0);
});
+
+ it("surfaces failures instead of silently changing the search scope", async () => {
+ mocks.search.mockRejectedValue(new Error("unavailable"));
+ await expect(searchSqlFileContents({ roots: ["/sql"], query: "users", fileFilter: "*.sql" })).rejects.toThrow("unavailable");
+ });
});
diff --git a/apps/desktop/src/lib/sql/__tests__/sqlFileTreeFilter.spec.ts b/apps/desktop/src/lib/sql/__tests__/sqlFileTreeFilter.spec.ts
index 0eac710b16..bd34b4e4c4 100644
--- a/apps/desktop/src/lib/sql/__tests__/sqlFileTreeFilter.spec.ts
+++ b/apps/desktop/src/lib/sql/__tests__/sqlFileTreeFilter.spec.ts
@@ -133,7 +133,7 @@ describe("sqlFileTreeFilter", () => {
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"]));
+ const result = filterAndSortSqlFileEntries(sampleEntries, "needle", "asc", new Set(["/sql/queries/get_orders.sql", "/sql/migrations/2024/01_init.sql"]), "content");
expect(result.entries.map((e) => e.name)).toEqual(["migrations", "queries"]);
const migrations = result.entries.find((e) => e.name === "migrations")!;
@@ -149,7 +149,7 @@ describe("sqlFileTreeFilter", () => {
it("preserves manual order for content-only matches", () => {
const manualOrder = { "/sql/queries": ["/sql/queries/select_user.sql", "/sql/queries/get_orders.sql"] };
- const result = filterAndSortSqlFileEntries(sampleEntries, "needle", "manual", new Set(["/sql/queries/get_orders.sql", "/sql/queries/select_user.sql"]), manualOrder);
+ const result = filterAndSortSqlFileEntries(sampleEntries, "needle", "manual", new Set(["/sql/queries/get_orders.sql", "/sql/queries/select_user.sql"]), "content", manualOrder);
expect(result.entries.map((entry) => entry.name)).toEqual(["queries"]);
expect(result.entries[0].children.map((entry) => entry.name)).toEqual(["select_user.sql", "get_orders.sql"]);
@@ -161,21 +161,28 @@ describe("sqlFileTreeFilter", () => {
// 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 result = filterAndSortSqlFileEntries(windowsEntries, "needle", "asc", new Set(["C:/sql/queries/get_orders.sql"]), "content");
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", () => {
+ it("defaults to name matching even when content hits are supplied", () => {
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(queries.children.map((c) => c.name)).toEqual(["select_user.sql"]);
expect(result.entries.map((e) => e.name)).toEqual(["migrations", "queries"]);
});
+ it("does not include name-only files or whole matching directories in content mode", () => {
+ const result = filterAndSortSqlFileEntries(sampleEntries, "queries", "asc", new Set(["/sql/queries/get_orders.sql"]), "content");
+ expect(result.entries.map((entry) => entry.name)).toEqual(["queries"]);
+ expect(result.entries[0].children.map((entry) => entry.name)).toEqual(["get_orders.sql"]);
+ expect(filterAndSortSqlFileEntries(sampleEntries, "user", "asc", new Set(), "content").entries).toEqual([]);
+ });
+
it("ignores an empty content-match set", () => {
const withEmpty = filterAndSortSqlFileEntries(sampleEntries, "user", "asc", new Set());
const withoutSet = filterAndSortSqlFileEntries(sampleEntries, "user", "asc");
diff --git a/apps/desktop/src/lib/sql/sqlFileContentSearch.ts b/apps/desktop/src/lib/sql/sqlFileContentSearch.ts
index 56228e2c3c..f22a9ca9db 100644
--- a/apps/desktop/src/lib/sql/sqlFileContentSearch.ts
+++ b/apps/desktop/src/lib/sql/sqlFileContentSearch.ts
@@ -1,131 +1,29 @@
import * as api from "@/lib/backend/api";
-import type { GlobalSearchMatch } from "@/lib/backend/api";
-import { formatSnippetLine, splitSearchMatchSegments, type SavedSqlLineMatch } from "@/lib/savedSql/savedSqlSearch";
+import type { SqlFileContentMatch, SqlFileContentSearchResult as BackendSearchResult } from "@/lib/backend/api";
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 SqlFileContentSearchResult extends BackendSearchResult {
+ matchesByPath: Map<string, SqlFileContentMatch>;
}
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 };
+ /** Use the same filter expression as the file tree, including extensionless files. */
+ fileFilter: string;
}
-/**
- * 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.
- */
+/** The dedicated scanner owns decoding, per-line grouping, preview limits and skipped reasons. */
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() };
+ if (!query || roots.length === 0) return { files: [], skippedFiles: [], truncated: false, 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);
+ const result = await api.searchSqlFileContents(roots, query, options.fileFilter);
+ // Keep files with no remaining preview budget: they still matched and must be visible.
+ return { ...result, matchesByPath: new Map(result.files.map((file) => [normalizeExternalSqlPath(file.path), file])) };
}
-/** 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 a2683f1f32..73bb1d68e9 100644
--- a/apps/desktop/src/lib/sql/sqlFileTreeFilter.ts
+++ b/apps/desktop/src/lib/sql/sqlFileTreeFilter.ts
@@ -5,6 +5,7 @@ import type { SqlFileOrder } from "@/lib/sqlFile/sqlFileOrder";
const SORT_ORDER_STORAGE_KEY = "dbx-sql-file-sort-order";
export type SqlFileSortOrder = "asc" | "desc" | "manual";
+export type SqlFileSearchMode = "name" | "content";
export const DEFAULT_SQL_FILE_SORT_ORDER: SqlFileSortOrder = "asc";
/** Read the name or manual sort order for external SQL files. */
@@ -68,9 +69,7 @@ function collectMatchingDescendantDirPaths(items: SqlFileEntry[], q: string, aut
if (item.name.toLowerCase().includes(q)) {
autoExpanded.add(item.path);
}
- if (item.children) {
- collectMatchingDescendantDirPaths(item.children, q, autoExpanded);
- }
+ collectMatchingDescendantDirPaths(item.children || [], q, autoExpanded);
}
}
}
@@ -78,17 +77,14 @@ function collectMatchingDescendantDirPaths(items: SqlFileEntry[], q: string, aut
/**
* Filters and sorts SQL file entries based on a search query and sort order.
* - If the query is empty, all entries are preserved and recursively sorted.
- * - If a directory's name matches the query, all of its contents are preserved (and recursively sorted),
+ * - In name mode, if a directory's name matches the query, all of its contents are preserved (and recursively sorted),
* and its path is added to `autoExpanded`.
* - 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.
+ * - Files match exclusively by name or by the supplied content hits, depending on the search mode.
+ * - Content mode keeps directories only as ancestors of matching files.
*/
-export function filterAndSortSqlFileEntries(entries: SqlFileEntry[], query: string, order: SqlFileSortOrder = "asc", contentMatchPaths?: ReadonlySet<string>, manualOrder: SqlFileOrder = {}): SqlFileFilterResult {
+export function filterAndSortSqlFileEntries(entries: SqlFileEntry[], query: string, order: SqlFileSortOrder = "asc", contentMatchPaths?: ReadonlySet<string>, mode: SqlFileSearchMode = "name", manualOrder: SqlFileOrder = {}): SqlFileFilterResult {
const ranks = new Map<string, number>();
if (order === "manual") {
for (const paths of Object.values(manualOrder)) paths.forEach((path, index) => ranks.set(path, index));
@@ -115,23 +111,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 (fileMatches(item)) {
+ const matches = mode === "content" ? contentMatchPaths?.has(normalizeExternalSqlPath(item.path)) === true : item.name.toLowerCase().includes(q);
+ if (matches) {
matchCount++;
result.push(item);
}
} else {
- const dirMatches = item.name.toLowerCase().includes(q);
+ const dirMatches = mode === "name" && item.name.toLowerCase().includes(q);
if (dirMatches) {
matchCount++;
autoExpanded.add(item.path);
diff --git a/src-tauri/src/commands/list_sql_files.rs b/src-tauri/src/commands/list_sql_files.rs
index 431fc65e92..1af13825a1 100644
--- a/src-tauri/src/commands/list_sql_files.rs
+++ b/src-tauri/src/commands/list_sql_files.rs
@@ -1,10 +1,16 @@
+use dbx_core::sql::decode_sql_file_bytes;
use regex::Regex;
use serde::Serialize;
use std::collections::HashSet;
+use std::io::Read;
use std::path::{Path, PathBuf};
const MAX_SCAN_DEPTH: usize = 10;
const DEFAULT_FILE_FILTER: &str = r"(?i)\.(sql|ddl)$";
+const MAX_SEARCH_FILE_BYTES: u64 = 32 * 1024 * 1024;
+const MAX_SEARCH_FILE_MATCHES: usize = 100;
+const MAX_SEARCH_MATCHES: usize = 1000;
+const MAX_SEARCH_LINE_CHARS: usize = 200;
/// Directories that are never interesting for SQL file browsing but are huge
/// (often tens of thousands of entries), which makes a recursive scan take
@@ -35,6 +41,56 @@ pub struct SqlFileEntry {
pub children: Vec<SqlFileEntry>,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SqlFileSearchSegment {
+ text: String,
+ matched: bool,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SqlFileSearchContext {
+ line_number: usize,
+ text: String,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SqlFileSearchMatch {
+ line_number: usize,
+ column: usize,
+ line_text: String,
+ segments: Vec<SqlFileSearchSegment>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ context_before: Option<SqlFileSearchContext>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ context_after: Option<SqlFileSearchContext>,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SqlFileSearchFile {
+ path: String,
+ matches: Vec<SqlFileSearchMatch>,
+ total_matches: usize,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SkippedSqlSearchFile {
+ path: String,
+ reason: String,
+}
+
+#[derive(Debug, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SqlFileSearchResult {
+ files: Vec<SqlFileSearchFile>,
+ skipped_files: Vec<SkippedSqlSearchFile>,
+ truncated: bool,
+}
+
fn validate_file_name(file_name: &str) -> Result<&str, String> {
let file_name = file_name.trim();
if file_name.is_empty() || file_name == "." || file_name == ".." || file_name.contains(['/', '\\']) {
@@ -176,6 +232,17 @@ fn scan_sql_files_with_directories(
visited: &mut HashSet<String>,
file_filter: &Regex,
include_empty_directories: bool,
+) -> Vec<SqlFileEntry> {
+ scan_sql_files_with_diagnostics(dir, depth, visited, file_filter, include_empty_directories, None)
+}
+
+fn scan_sql_files_with_diagnostics(
+ dir: &Path,
+ depth: usize,
+ visited: &mut HashSet<String>,
+ file_filter: &Regex,
+ include_empty_directories: bool,
+ mut skipped_files: Option<&mut Vec<SkippedSqlSearchFile>>,
) -> Vec<SqlFileEntry> {
if depth > MAX_SCAN_DEPTH {
return vec![];
@@ -194,13 +261,41 @@ fn scan_sql_files_with_directories(
let mut entries = Vec::new();
let dir_entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
- Err(_) => return entries,
+ Err(_) => {
+ if let Some(skipped) = skipped_files.as_deref_mut() {
+ skipped.push(SkippedSqlSearchFile {
+ path: dir.to_string_lossy().into_owned(),
+ reason: "unreadable".to_string(),
+ });
+ }
+ return entries;
+ }
};
- for entry in dir_entries.flatten() {
+ for entry in dir_entries {
+ let entry = match entry {
+ Ok(entry) => entry,
+ Err(_) => {
+ if let Some(skipped) = skipped_files.as_deref_mut() {
+ skipped.push(SkippedSqlSearchFile {
+ path: dir.to_string_lossy().into_owned(),
+ reason: "unreadable".to_string(),
+ });
+ }
+ continue;
+ }
+ };
let file_type = match entry.file_type() {
Ok(ft) => ft,
- Err(_) => continue,
+ Err(_) => {
+ if let Some(skipped) = skipped_files.as_deref_mut() {
+ skipped.push(SkippedSqlSearchFile {
+ path: entry.path().to_string_lossy().into_owned(),
+ reason: "unreadable".to_string(),
+ });
+ }
+ continue;
+ }
};
let path = entry.path();
let name = match path.file_name().and_then(|n| n.to_str()) {
@@ -212,8 +307,14 @@ fn scan_sql_files_with_directories(
if is_pruned_dir(&name) {
continue;
}
- let children =
- scan_sql_files_with_directories(&path, depth + 1, visited, file_filter, include_empty_directories);
+ let children = scan_sql_files_with_diagnostics(
+ &path,
+ depth + 1,
+ visited,
+ file_filter,
+ include_empty_directories,
+ skipped_files.as_deref_mut(),
+ );
if include_empty_directories || !children.is_empty() {
entries.push(SqlFileEntry { name, path: path.to_string_lossy().to_string(), is_dir: true, children });
}
@@ -264,6 +365,218 @@ pub async fn list_sql_files_in_folder(
.map_err(|e| format!("Failed to scan folder: {e}"))?
}
+// Lowercasing can expand a character (for example, İ). Translate matching
+// offsets back to the original text before computing editor positions.
+fn original_search_range(text: &str, lower_start: usize, lower_end: usize) -> (usize, usize) {
+ let mut lower_offset = 0;
+ let mut original_start = None;
+ for (offset, character) in text.char_indices() {
+ let next_lower_offset = lower_offset + character.to_lowercase().map(char::len_utf8).sum::<usize>();
+ if original_start.is_none() && next_lower_offset > lower_start {
+ original_start = Some(offset);
+ }
+ if next_lower_offset >= lower_end {
+ return (original_start.unwrap_or(offset), offset + character.len_utf8());
+ }
+ lower_offset = next_lower_offset;
+ }
+ (original_start.unwrap_or(text.len()), text.len())
+}
+
+fn search_context(text: &str, line_number: usize) -> Option<SqlFileSearchContext> {
+ let text = text.trim();
+ if text.is_empty() {
+ return None;
+ }
+ let end = text.char_indices().nth(MAX_SEARCH_LINE_CHARS).map_or(text.len(), |(offset, _)| offset);
+ Some(SqlFileSearchContext {
+ line_number,
+ text: format!("{}{}", &text[..end], if end < text.len() { "..." } else { "" }),
+ })
+}
+
+fn search_snippet(
+ line: &str,
+ query: &str,
+ first_match: usize,
+ first_match_end: usize,
+) -> (String, Vec<SqlFileSearchSegment>) {
+ let first_match_char = line[..first_match].chars().count();
+ let start_char = first_match_char.saturating_sub(20);
+ let start = line.char_indices().nth(start_char).map_or(line.len(), |(offset, _)| offset);
+ let end = line[start..].char_indices().nth(MAX_SEARCH_LINE_CHARS).map_or(line.len(), |(offset, _)| start + offset);
+ let snippet = &line[start..end];
+ let lower = snippet.to_lowercase();
+ let mut segments = Vec::new();
+ if start > 0 {
+ segments.push(SqlFileSearchSegment { text: "...".to_string(), matched: false });
+ }
+ let mut cursor = 0;
+ let mut lower_cursor = 0;
+ // A query itself can exceed the preview budget. Highlight the visible part
+ // of its first match even though the clipped preview lacks the full query.
+ if first_match_end > end {
+ let match_start = first_match - start;
+ if match_start > 0 {
+ segments.push(SqlFileSearchSegment { text: snippet[..match_start].to_string(), matched: false });
+ }
+ segments.push(SqlFileSearchSegment { text: snippet[match_start..].to_string(), matched: true });
+ cursor = snippet.len();
+ lower_cursor = lower.len();
+ }
+ while let Some(relative_start) = lower[lower_cursor..].find(query) {
+ let lower_start = lower_cursor + relative_start;
+ let lower_end = lower_start + query.len();
+ let (match_start, match_end) = original_search_range(snippet, lower_start, lower_end);
+ if match_start > cursor {
+ segments.push(SqlFileSearchSegment { text: snippet[cursor..match_start].to_string(), matched: false });
+ }
+ if match_end > cursor {
+ segments.push(SqlFileSearchSegment {
+ text: snippet[match_start.max(cursor)..match_end].to_string(),
+ matched: true,
+ });
+ cursor = match_end;
+ }
+ lower_cursor = lower_end;
+ }
+ if cursor < snippet.len() {
+ segments.push(SqlFileSearchSegment { text: snippet[cursor..].to_string(), matched: false });
+ }
+ if end < line.len() {
+ segments.push(SqlFileSearchSegment { text: "...".to_string(), matched: false });
+ }
+ let line_text = segments.iter().map(|segment| segment.text.as_str()).collect::<String>();
+ (line_text, segments)
+}
+
+fn search_sql_text(path: String, text: &str, query: &str, remaining_matches: &mut usize) -> SqlFileSearchFile {
+ let mut result = SqlFileSearchFile { path, matches: Vec::new(), total_matches: 0 };
+ let mut previous_line = None;
+ let mut lines = text.split('\n').enumerate().peekable();
+ while let Some((index, raw_line)) = lines.next() {
+ let line = raw_line.strip_suffix('\r').unwrap_or(raw_line);
+ if let Some(lower_start) = line.to_lowercase().find(query) {
+ result.total_matches += 1;
+ if result.matches.len() < MAX_SEARCH_FILE_MATCHES && *remaining_matches > 0 {
+ let (start, end) = original_search_range(line, lower_start, lower_start + query.len());
+ let (line_text, segments) = search_snippet(line, query, start, end);
+ result.matches.push(SqlFileSearchMatch {
+ line_number: index + 1,
+ // CodeMirror/JavaScript positions count UTF-16 code units.
+ column: line[..start].encode_utf16().count() + 1,
+ line_text,
+ segments,
+ context_before: previous_line.and_then(|text| search_context(text, index)),
+ context_after: lines.peek().and_then(|(_, text)| search_context(text, index + 2)),
+ });
+ *remaining_matches -= 1;
+ }
+ }
+ previous_line = Some(line);
+ }
+ result
+}
+
+fn read_sql_search_file(root: &Path, path: &Path) -> Result<String, &'static str> {
+ let metadata = std::fs::symlink_metadata(path).map_err(|_| "unreadable")?;
+ if !metadata.file_type().is_file() {
+ return Err("notRegularFile");
+ }
+ let canonical = std::fs::canonicalize(path).map_err(|_| "unreadable")?;
+ if !canonical.starts_with(root) {
+ return Err("outsideRoot");
+ }
+ let file = std::fs::File::open(&canonical).map_err(|_| "unreadable")?;
+ let metadata = file.metadata().map_err(|_| "unreadable")?;
+ if !metadata.is_file() {
+ return Err("notRegularFile");
+ }
+ if metadata.len() > MAX_SEARCH_FILE_BYTES {
+ return Err("tooLarge");
+ }
+ let mut bytes = Vec::with_capacity(metadata.len() as usize);
+ file.take(MAX_SEARCH_FILE_BYTES + 1).read_to_end(&mut bytes).map_err(|_| "unreadable")?;
+ if bytes.len() as u64 > MAX_SEARCH_FILE_BYTES {
+ return Err("tooLarge");
+ }
+ decode_sql_file_bytes(&bytes).map_err(|_| "invalidEncoding")
+}
+
+fn search_sql_entries(
+ entries: Vec<SqlFileEntry>,
+ root: &Path,
+ query: &str,
+ visited_files: &mut HashSet<String>,
+ remaining_matches: &mut usize,
+ result: &mut SqlFileSearchResult,
+) {
+ for entry in entries {
+ if entry.is_dir {
+ search_sql_entries(entry.children, root, query, visited_files, remaining_matches, result);
+ continue;
+ }
+ // Preserve the same display-path identities as the tree, including on
+ // Windows. Overlapping roots must not consume the snippet budget twice.
+ if !visited_files.insert(entry.path.clone()) {
+ continue;
+ }
+ match read_sql_search_file(root, Path::new(&entry.path)) {
+ Ok(text) => {
+ let file = search_sql_text(entry.path, &text, query, remaining_matches);
+ if file.total_matches > 0 {
+ result.truncated |= file.matches.len() < file.total_matches;
+ result.files.push(file);
+ }
+ }
+ Err(reason) => {
+ result.skipped_files.push(SkippedSqlSearchFile { path: entry.path, reason: reason.to_string() })
+ }
+ }
+ }
+}
+
+#[tauri::command]
+pub async fn search_sql_file_contents(
+ roots: Vec<String>,
+ file_filter: Option<String>,
+ query: String,
+) -> Result<SqlFileSearchResult, String> {
+ let query = query.trim().to_lowercase();
+ if query.is_empty() || roots.is_empty() {
+ return Ok(SqlFileSearchResult::default());
+ }
+ let file_filter = compile_file_filter(file_filter.as_deref().unwrap_or(DEFAULT_FILE_FILTER))?;
+ tauri::async_runtime::spawn_blocking(move || {
+ let mut result = SqlFileSearchResult::default();
+ let mut visited_files = HashSet::new();
+ let mut remaining_matches = MAX_SEARCH_MATCHES;
+ for root in roots {
+ let canonical = match canonical_directory(Path::new(&root), "SQL root folder") {
+ Ok(path) => path,
+ _ => {
+ result.skipped_files.push(SkippedSqlSearchFile { path: root, reason: "unreadable".to_string() });
+ continue;
+ }
+ };
+ let entries = scan_sql_files_with_diagnostics(
+ Path::new(&root),
+ 0,
+ &mut HashSet::new(),
+ &file_filter,
+ false,
+ Some(&mut result.skipped_files),
+ );
+ // Even after the preview budget is exhausted, scan every candidate
+ // so content-only files remain visible and line counts stay exact.
+ search_sql_entries(entries, &canonical, &query, &mut visited_files, &mut remaining_matches, &mut result);
+ }
+ result
+ })
+ .await
+ .map_err(|error| format!("Failed to search SQL files: {error}"))
+}
+
#[tauri::command]
pub async fn create_sql_file_in_folder(
root_path: String,
@@ -398,6 +711,94 @@ pub async fn delete_sql_folder_in_folder(root_path: String, folder_path: String)
mod tests {
use super::*;
+ #[test]
+ fn content_search_groups_matching_lines_and_uses_utf16_editor_columns() {
+ let mut remaining = MAX_SEARCH_MATCHES;
+ let result = search_sql_text(
+ "query.sql".into(),
+ "-- context\r\n😀İ needle needle\r\nSELECT 1",
+ "needle",
+ &mut remaining,
+ );
+ assert_eq!(result.total_matches, 1);
+ assert_eq!(result.matches.len(), 1);
+ assert_eq!(result.matches[0].line_number, 2);
+ assert_eq!(result.matches[0].column, 5);
+ assert_eq!(result.matches[0].segments.iter().filter(|segment| segment.matched).count(), 2);
+ assert_eq!(result.matches[0].context_before.as_ref().unwrap().line_number, 1);
+ assert_eq!(result.matches[0].context_after.as_ref().unwrap().line_number, 3);
+
+ let expanded_case = search_sql_text("query.sql".into(), "İ needle", "needle", &mut remaining);
+ assert_eq!(expanded_case.matches[0].column, 3);
+ }
+
+ #[test]
+ fn content_search_limits_previews_without_losing_counts_or_later_files() {
+ let text = vec!["SELECT needle"; 150].join("\n");
+ let mut remaining = MAX_SEARCH_FILE_MATCHES + 1;
+ let first = search_sql_text("first.sql".into(), &text, "needle", &mut remaining);
+ assert_eq!(first.total_matches, 150);
+ assert_eq!(first.matches.len(), MAX_SEARCH_FILE_MATCHES);
+ let second = search_sql_text("second.sql".into(), &text, "needle", &mut remaining);
+ assert_eq!(second.total_matches, 150);
+ assert_eq!(second.matches.len(), 1);
+ let third = search_sql_text("third.sql".into(), &text, "needle", &mut remaining);
+ assert_eq!(third.total_matches, 150);
+ assert!(third.matches.is_empty());
+ }
+
+ #[test]
+ fn content_search_centers_long_snippets_around_the_original_match() {
+ let text = format!("{}needle trailing", "长".repeat(250));
+ let mut remaining = MAX_SEARCH_MATCHES;
+ let result = search_sql_text("query.sql".into(), &text, "needle", &mut remaining);
+ let snippet = &result.matches[0];
+ assert_eq!(snippet.column, 251);
+ assert!(snippet.line_text.starts_with("..."));
+ assert!(snippet.line_text.chars().count() <= MAX_SEARCH_LINE_CHARS + 6);
+ assert_eq!(
+ snippet
+ .segments
+ .iter()
+ .filter(|segment| segment.matched)
+ .map(|segment| segment.text.as_str())
+ .collect::<Vec<_>>(),
+ vec!["needle"]
+ );
+ }
+
+ #[tokio::test]
+ async fn content_search_preserves_tree_filters_decoding_and_skipped_reasons() {
+ let root = std::env::temp_dir().join(format!("dbx-sql-content-search-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(root.join("node_modules")).unwrap();
+ std::fs::write(root.join(".gitignore"), "*.sql").unwrap();
+ std::fs::write(root.join("README"), "请求方式").unwrap();
+ std::fs::write(root.join(".hidden.sql"), "请求方式").unwrap();
+ std::fs::write(root.join("ignored.txt"), "请求方式").unwrap();
+ std::fs::write(root.join("node_modules/excluded.sql"), "请求方式").unwrap();
+ let mut utf16 = vec![0xff, 0xfe];
+ for unit in "请求方式".encode_utf16() {
+ utf16.extend_from_slice(&unit.to_le_bytes());
+ }
+ std::fs::write(root.join("utf16.sql"), utf16).unwrap();
+ std::fs::write(root.join("gbk.sql"), [0xc7, 0xeb, 0xc7, 0xf3, 0xb7, 0xbd, 0xca, 0xbd]).unwrap();
+ std::fs::File::create(root.join("large.sql")).unwrap().set_len(MAX_SEARCH_FILE_BYTES + 1).unwrap();
+ let root_string = root.to_string_lossy().into_owned();
+ let result = search_sql_file_contents(
+ vec![root_string.clone(), root_string],
+ Some(r"(?i)(\.sql$|^README$)".into()),
+ "请求方式".into(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(result.files.len(), 4);
+ assert!(result.files.iter().all(|file| file.total_matches == 1));
+ assert_eq!(result.skipped_files.len(), 1);
+ assert_eq!(result.skipped_files[0].reason, "tooLarge");
+ assert!(!result.truncated);
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
fn collect_file_names(entries: &[SqlFileEntry], names: &mut Vec<String>) {
for entry in entries {
if entry.is_dir {
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 54c83f1150..97cf34bb61 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2631,6 +2631,7 @@ pub fn run() {
commands::external_sql::write_external_sql_file,
commands::external_sql::save_external_sql_file,
commands::list_sql_files::list_sql_files_in_folder,
+ commands::list_sql_files::search_sql_file_contents,
commands::list_sql_files::create_sql_file_in_folder,
commands::list_sql_files::rename_sql_file_in_folder,
commands::list_sql_files::delete_sql_file_in_folder,