Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(sql-file): add configurable file name filter

andystenhef725c50b2c42
diff --git a/Cargo.lock b/Cargo.lock
index 88be6502ef..16de5320c6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2024,6 +2024,7 @@ dependencies = [
"percent-encoding",
"portpicker",
"redis",
+ "regex",
"reqwest 0.12.28",
"russh",
"rust_decimal",
diff --git a/apps/desktop/src/components/layout/SqlFilePanel.vue b/apps/desktop/src/components/layout/SqlFilePanel.vue
index 1b63966d02..d8ec428d13 100644
--- a/apps/desktop/src/components/layout/SqlFilePanel.vue
+++ b/apps/desktop/src/components/layout/SqlFilePanel.vue
@@ -1,10 +1,11 @@
<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useI18n } from "vue-i18n";
-import { FolderOpen, FileCode, FolderClosed, ChevronRight, ChevronDown, X, Trash2, RefreshCw, FolderSearch, Copy, Play, ChevronsUpDown, ChevronsDownUp, FilePlus, Pencil } from "@lucide/vue";
+import { FolderOpen, FileCode, FolderClosed, ChevronRight, ChevronDown, X, Trash2, RefreshCw, FolderSearch, Copy, Play, ChevronsUpDown, ChevronsDownUp, Settings, FilePlus, Pencil } from "@lucide/vue";
import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import LightTooltip from "@/components/ui/LightTooltip.vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import { useQueryStore } from "@/stores/queryStore";
@@ -17,7 +18,7 @@ import { forgetExternalSqlFileTarget, moveExternalSqlFileTarget, resolveExternal
import { externalSqlFileOpenErrorMessage, formatSqlFileSize, isExternalSqlFileTooLargeError } from "@/lib/sql/sqlFileOpen";
import * as api from "@/lib/backend/api";
import type { SqlFileEntry } from "@/lib/backend/api";
-import { getSqlFileFolderPaths, saveSqlFileFolderPaths, notifySqlFileFoldersChanged } from "@/lib/sqlFile/sqlFileFolders";
+import { getSqlFileFilter, getSqlFileFolderPaths, saveSqlFileFilter, saveSqlFileFolderPaths, notifySqlFileFoldersChanged } from "@/lib/sqlFile/sqlFileFolders";
import { orderedListRangeAnchorIndex, orderedListSelectionIntent, type OrderedListSelectionItem } from "@/lib/selection/orderedListSelection";
const emit = defineEmits<{
@@ -38,6 +39,9 @@ interface FolderState {
}
const folders = ref<FolderState[]>([]);
+const filterSettingsOpen = ref(false);
+const fileFilterDraft = ref(getSqlFileFilter());
+const fileFilterRegexExample = ".*[.](sql|sh|py)$";
// Right-click target. `kind` discriminates between a folder header, a tree
// directory entry, and a tree file entry. `folderPath` is the owning top-level
@@ -112,12 +116,12 @@ async function addFolder(folderPath: string) {
// Re-scan a single top-level folder and replace its entries. Mutated via the
// reactive proxy (folders.value[idx]) so Vue tracks the change — see the note
// in addFolder above.
-async function loadFolderEntries(folderPath: string) {
+async function loadFolderEntries(folderPath: string): Promise<string | null> {
const idx = folders.value.findIndex((f) => f.path === folderPath);
- if (idx === -1) return;
+ if (idx === -1) return null;
folders.value[idx].loading = true;
try {
- const entries = await api.listSqlFilesInFolder(folderPath);
+ const entries = await api.listSqlFilesInFolder(folderPath, getSqlFileFilter());
const target = folders.value.findIndex((f) => f.path === folderPath);
if (target !== -1) {
folders.value[target].entries = entries;
@@ -132,13 +136,16 @@ async function loadFolderEntries(folderPath: string) {
folders.value[target].expanded = nextExpanded;
}
} catch (e: any) {
- toast(t("sqlFileTree.loadFailed", { message: e?.message || String(e) }), 5000);
+ const message = e?.message || String(e);
+ toast(t("sqlFileTree.loadFailed", { message }), 5000);
+ return message;
} finally {
const target = folders.value.findIndex((f) => f.path === folderPath);
if (target !== -1) {
folders.value[target].loading = false;
}
}
+ return null;
}
function collectPaths(entries: SqlFileEntry[], into: Set<string>) {
@@ -160,6 +167,24 @@ async function refreshAll() {
toast(t("sqlFileTree.refreshed"), 1500);
}
+async function saveFileFilter() {
+ const previousFilter = getSqlFileFilter();
+ saveSqlFileFilter(fileFilterDraft.value);
+ const errors = await Promise.all(folders.value.map((f) => loadFolderEntries(f.path)));
+ // An unparsable pattern must not survive in localStorage: it would fail
+ // every later refresh and silently empty Quick Open until it is fixed.
+ const invalidFilter = errors.find((message) => message?.startsWith("Invalid file filter"));
+ if (invalidFilter) {
+ saveSqlFileFilter(previousFilter);
+ await Promise.all(folders.value.map((f) => loadFolderEntries(f.path)));
+ toast(t("sqlFileTree.filterInvalid", { message: invalidFilter }), 5000);
+ return;
+ }
+ filterSettingsOpen.value = false;
+ notifySqlFileFoldersChanged();
+ toast(t("sqlFileTree.refreshed"), 1500);
+}
+
async function reloadFolderAfterMutation(folderPath: string) {
await loadFolderEntries(folderPath);
notifySqlFileFoldersChanged();
@@ -507,6 +532,19 @@ function clearContextTarget() {
<div class="h-9 flex items-center gap-1 px-2 border-b shrink-0 bg-muted/20">
<span class="text-[13px] font-medium">{{ t("sqlFileTree.title") }}</span>
<span class="flex-1" />
+ <LightTooltip :text="t('sqlFileTree.filterSettings')" side="bottom" :delay="0" :close-delay="0" nowrap>
+ <Button
+ variant="ghost"
+ size="icon"
+ class="h-5 w-5"
+ @click="
+ fileFilterDraft = getSqlFileFilter();
+ filterSettingsOpen = true;
+ "
+ >
+ <Settings class="h-3 w-3" />
+ </Button>
+ </LightTooltip>
<LightTooltip v-if="folders.length > 0" :text="t('sqlFileTree.refreshAll')" side="bottom" :delay="0" :close-delay="0" nowrap>
<Button variant="ghost" size="icon" class="h-5 w-5" @click="refreshAll">
<RefreshCw class="h-3 w-3" />
@@ -649,6 +687,23 @@ function clearContextTarget() {
</template>
</CustomContextMenu>
+ <Dialog v-model:open="filterSettingsOpen">
+ <DialogContent class="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{{ t("sqlFileTree.filterSettings") }}</DialogTitle>
+ </DialogHeader>
+ <div class="grid gap-2 py-2">
+ <Label for="sql-file-filter">{{ t("sqlFileTree.fileFilter") }}</Label>
+ <Input id="sql-file-filter" v-model="fileFilterDraft" :placeholder="t('sqlFileTree.fileFilterPlaceholder')" @keydown.enter="saveFileFilter" />
+ <p class="text-xs text-muted-foreground">{{ t("sqlFileTree.fileFilterHint", { regex: fileFilterRegexExample }) }}</p>
+ </div>
+ <DialogFooter>
+ <Button type="button" variant="outline" @click="filterSettingsOpen = false">{{ t("common.cancel") }}</Button>
+ <Button type="button" @click="saveFileFilter">{{ t("common.save") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
<Dialog :open="showCreateDialog" @update:open="(open) => (showCreateDialog = open)">
<DialogContent class="sm:max-w-[380px]">
<DialogHeader>
diff --git a/apps/desktop/src/components/layout/__tests__/SqlFilePanel.spec.ts b/apps/desktop/src/components/layout/__tests__/SqlFilePanel.spec.ts
index cbcecf66d9..d8c8a69ed9 100644
--- a/apps/desktop/src/components/layout/__tests__/SqlFilePanel.spec.ts
+++ b/apps/desktop/src/components/layout/__tests__/SqlFilePanel.spec.ts
@@ -46,3 +46,16 @@ describe("SqlFilePanel directory actions", () => {
expect(panelSource).toContain('@click.stop="openCreateDialog(folder.path, entry.path)"');
});
});
+
+describe("SqlFilePanel file filter", () => {
+ it("restores the previous filter when the backend rejects the saved pattern", () => {
+ expect(panelSource).toContain('message?.startsWith("Invalid file filter")');
+ expect(panelSource).toContain("saveSqlFileFilter(previousFilter)");
+ expect(panelSource).toContain('t("sqlFileTree.filterInvalid"');
+ });
+
+ it("renders the translated filter placeholder", () => {
+ expect(panelSource).toContain("t('sqlFileTree.fileFilterPlaceholder')");
+ expect(panelSource).not.toContain("const fileFilterPlaceholder =");
+ });
+});
diff --git a/apps/desktop/src/composables/__tests__/useQuickOpen.spec.ts b/apps/desktop/src/composables/__tests__/useQuickOpen.spec.ts
index 212627ba45..fb7c12220a 100644
--- a/apps/desktop/src/composables/__tests__/useQuickOpen.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useQuickOpen.spec.ts
@@ -2,7 +2,7 @@ import { nextTick } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { matchQuickOpenText, useQuickOpen } from "@/composables/useQuickOpen";
import * as api from "@/lib/backend/api";
-import { getSqlFileFolderPaths, sqlFileFoldersVersion } from "@/lib/sqlFile/sqlFileFolders";
+import { getSqlFileFilter, getSqlFileFolderPaths, sqlFileFoldersVersion } from "@/lib/sqlFile/sqlFileFolders";
import { useConnectionStore } from "@/stores/connectionStore";
import { useSavedSqlStore } from "@/stores/savedSqlStore";
@@ -22,6 +22,7 @@ vi.mock("@/lib/backend/api", () => ({
vi.mock("@/lib/sqlFile/sqlFileFolders", async () => {
const { ref } = await import("vue");
return {
+ getSqlFileFilter: vi.fn(() => "*.sql"),
getSqlFileFolderPaths: vi.fn(),
sqlFileFoldersVersion: ref(0),
};
@@ -68,7 +69,7 @@ describe("useQuickOpen", () => {
const { filteredItems, loadExternalSqlFiles, setQuery } = useQuickOpen();
const initialLoad = loadExternalSqlFiles();
- expect(api.listSqlFilesInFolder).toHaveBeenCalledWith("/old");
+ expect(api.listSqlFilesInFolder).toHaveBeenCalledWith("/old", getSqlFileFilter());
sqlFileFoldersVersion.value++;
await nextTick();
@@ -76,7 +77,7 @@ describe("useQuickOpen", () => {
await initialLoad;
expect(api.listSqlFilesInFolder).toHaveBeenCalledTimes(2);
- expect(api.listSqlFilesInFolder).toHaveBeenLastCalledWith("/new");
+ expect(api.listSqlFilesInFolder).toHaveBeenLastCalledWith("/new", getSqlFileFilter());
setQuery(".sql");
expect(filteredItems.value.map((item) => item.label)).toContain("new.sql");
expect(filteredItems.value.map((item) => item.label)).not.toContain("old.sql");
diff --git a/apps/desktop/src/composables/useQuickOpen.ts b/apps/desktop/src/composables/useQuickOpen.ts
index 9f63059ad5..bff2ccaff8 100644
--- a/apps/desktop/src/composables/useQuickOpen.ts
+++ b/apps/desktop/src/composables/useQuickOpen.ts
@@ -6,7 +6,7 @@ import { useConnectionStore } from "@/stores/connectionStore";
import { useSavedSqlStore } from "@/stores/savedSqlStore";
import * as api from "@/lib/backend/api";
import type { SqlFileEntry } from "@/lib/backend/api";
-import { getSqlFileFolderPaths, sqlFileFoldersVersion } from "@/lib/sqlFile/sqlFileFolders";
+import { getSqlFileFilter, getSqlFileFolderPaths, sqlFileFoldersVersion } from "@/lib/sqlFile/sqlFileFolders";
import i18n from "@/i18n";
const REMOTE_SEARCH_DEBOUNCE_MS = 180;
@@ -258,7 +258,7 @@ export function useQuickOpen() {
const allEntries: Array<{ entry: SqlFileEntry; rootFolder: string }> = [];
for (const folderPath of folderPaths) {
try {
- const entries = await api.listSqlFilesInFolder(folderPath);
+ const entries = await api.listSqlFilesInFolder(folderPath, getSqlFileFilter());
const collected: SqlFileEntry[] = [];
collectSqlFileEntries(entries, collected);
const rootName = folderNameFromPath(folderPath);
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index aab115fa74..b578b68882 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -5815,6 +5815,11 @@ export default {
deleteFailed: "Failed to delete SQL file: {message}",
expandAll: "Expand all",
collapseAll: "Collapse all",
+ filterSettings: "File Filter",
+ fileFilter: "File name filter",
+ fileFilterPlaceholder: "File name filter",
+ filterInvalid: "Invalid file filter, kept the previous one: {message}",
+ fileFilterHint: "Use a glob such as *.sql or *.sh, or a regular expression such as {regex}.",
},
diff: {
progress: {
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 678236a895..cfbb1da9cd 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -7421,6 +7421,11 @@ export default withEnglishFallback({
deleteFailed: "No se pudo eliminar el archivo SQL: {message}",
expandAll: "Expandir todo",
collapseAll: "Contraer todo",
+ filterSettings: "Filtro de archivos",
+ fileFilter: "Filtro de nombre de archivo",
+ fileFilterPlaceholder: "Filtro de nombre de archivo",
+ filterInvalid: "Filtro de archivos no válido; se conserva el anterior: {message}",
+ fileFilterHint: "Use un comodín como *.sql o *.sh, o una expresión regular como {regex}.",
},
mqTopics: {
title: "Administración de temas",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 5bbea0ffb0..76a13f1350 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -7422,6 +7422,11 @@ export default withEnglishFallback({
deleteFailed: "Impossibile eliminare il file SQL: {message}",
expandAll: "Espandi tutto",
collapseAll: "Comprimi tutto",
+ filterSettings: "Filtro file",
+ fileFilter: "Filtro nome file",
+ fileFilterPlaceholder: "Filtro nome file",
+ filterInvalid: "Filtro file non valido; viene mantenuto il precedente: {message}",
+ fileFilterHint: "Usa un carattere jolly come *.sql o *.sh oppure un'espressione regolare come {regex}.",
},
mqTopics: {
title: "Gestione topic",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index d9a3a4e23e..44baac8c87 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -7473,6 +7473,11 @@ export default withEnglishFallback({
deleteFailed: "SQLファイルを削除できませんでした: {message}",
expandAll: "すべて展開",
collapseAll: "すべて折りたたむ",
+ filterSettings: "ファイルフィルター",
+ fileFilter: "ファイル名フィルター",
+ fileFilterPlaceholder: "ファイル名フィルター",
+ filterInvalid: "ファイルフィルタが無効なため、以前の設定を維持しました:{message}",
+ fileFilterHint: "*.sql や *.sh のようなワイルドカード、または {regex} のような正規表現を使用できます。",
},
mqTopics: {
title: "トピック管理",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index ce036723c1..6d030768d6 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -5240,6 +5240,11 @@ export default withEnglishFallback({
deleteFailed: "SQL 파일을 삭제하지 못했습니다: {message}",
expandAll: "모두 펼치기",
collapseAll: "모두 접기",
+ filterSettings: "파일 필터",
+ fileFilter: "파일 이름 필터",
+ fileFilterPlaceholder: "파일 이름 필터",
+ filterInvalid: "파일 필터가 잘못되어 이전 설정을 유지합니다: {message}",
+ fileFilterHint: "*.sql 또는 *.sh 같은 와일드카드나 {regex} 같은 정규식을 사용할 수 있습니다.",
},
diff: {
progress: {
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index b168ba1fba..f993ac334d 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -7423,6 +7423,11 @@ export default withEnglishFallback({
deleteFailed: "Falha ao excluir o arquivo SQL: {message}",
expandAll: "Expandir todos",
collapseAll: "Recolher todos",
+ filterSettings: "Filtro de arquivos",
+ fileFilter: "Filtro de nome de arquivo",
+ fileFilterPlaceholder: "Filtro de nome de arquivo",
+ filterInvalid: "Filtro de arquivo inválido; o anterior foi mantido: {message}",
+ fileFilterHint: "Use um curinga como *.sql ou *.sh, ou uma expressão regular como {regex}.",
},
mqTopics: {
title: "Gerenciamento de tópicos",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 74961b69b8..e23be266f6 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -5799,6 +5799,11 @@ export default withEnglishFallback({
deleteFailed: "删除 SQL 文件失败: {message}",
expandAll: "全部展开",
collapseAll: "全部折叠",
+ filterSettings: "文件过滤",
+ fileFilter: "文件名过滤规则",
+ fileFilterPlaceholder: "文件名过滤规则",
+ filterInvalid: "文件过滤规则无效,已保留原规则:{message}",
+ fileFilterHint: "支持通配符(如 *.sql、*.sh)或正则表达式(如 {regex})。",
},
diff: {
progress: {
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 89740360f0..344b93850a 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -7411,6 +7411,11 @@ export default withEnglishFallback({
deleteFailed: "刪除 SQL 檔案失敗: {message}",
expandAll: "全部展開",
collapseAll: "全部摺疊",
+ filterSettings: "檔案篩選",
+ fileFilter: "檔案名稱篩選規則",
+ fileFilterPlaceholder: "檔案名稱篩選規則",
+ filterInvalid: "檔案篩選規則無效,已保留原規則:{message}",
+ fileFilterHint: "支援萬用字元(如 *.sql、*.sh)或正則表示式(如 {regex})。",
},
mqTopics: {
title: "主題管理",
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 4515395771..38e99d9f2e 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -2223,7 +2223,7 @@ export interface SqlFileEntry {
children: SqlFileEntry[];
}
-export async function listSqlFilesInFolder(_folderPath: string): Promise<SqlFileEntry[]> {
+export async function listSqlFilesInFolder(_folderPath: string, _fileFilter?: string): Promise<SqlFileEntry[]> {
throw new Error("Listing SQL files in a folder 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 89c97bdf95..7f58ac7fde 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -888,8 +888,8 @@ export interface SqlFileEntry {
children: SqlFileEntry[];
}
-export async function listSqlFilesInFolder(folderPath: string): Promise<SqlFileEntry[]> {
- return invoke("list_sql_files_in_folder", { folderPath });
+export async function listSqlFilesInFolder(folderPath: string, fileFilter?: string): Promise<SqlFileEntry[]> {
+ return invoke("list_sql_files_in_folder", { folderPath, fileFilter });
}
export async function createSqlFileInFolder(rootPath: string, directoryPath: string, fileName: string): Promise<string> {
diff --git a/apps/desktop/src/lib/sqlFile/sqlFileFolders.ts b/apps/desktop/src/lib/sqlFile/sqlFileFolders.ts
index 5839eb15e0..65f8fae8eb 100644
--- a/apps/desktop/src/lib/sqlFile/sqlFileFolders.ts
+++ b/apps/desktop/src/lib/sqlFile/sqlFileFolders.ts
@@ -2,6 +2,8 @@ import { ref } from "vue";
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
const STORAGE_KEY = "dbx-sql-file-folders";
+const FILTER_STORAGE_KEY = "dbx-sql-file-filter";
+export const DEFAULT_SQL_FILE_FILTER = "*.sql";
/**
* Shared reactive version counter — bumped whenever SQL file folder paths change.
@@ -22,6 +24,18 @@ export function getSqlFileFolderPaths(): string[] {
}
}
+/** Read the file-name filter used by the external SQL file browser. */
+export function getSqlFileFilter(): string {
+ const filter = safeLocalStorageGet(FILTER_STORAGE_KEY)?.trim();
+ return filter || DEFAULT_SQL_FILE_FILTER;
+}
+
+/** Persist the file-name filter and invalidate cached external file listings. */
+export function saveSqlFileFilter(filter: string): void {
+ safeLocalStorageSet(FILTER_STORAGE_KEY, filter.trim() || DEFAULT_SQL_FILE_FILTER);
+ sqlFileFoldersVersion.value++;
+}
+
/** Persist folder paths to localStorage and notify subscribers. */
export function saveSqlFileFolderPaths(paths: string[]): void {
safeLocalStorageSet(STORAGE_KEY, JSON.stringify(paths));
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index c551697e29..fed9cb9e64 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -55,6 +55,7 @@ portpicker = "0.1.1"
tiberius = { version = "0.12.3", default-features = false, features = ["tds73", "chrono", "rust_decimal", "rustls", "sql-browser-tokio"] }
tokio-util = { version = "0.7", features = ["compat"] }
reqwest = { version = "0.12", features = ["json", "stream"] }
+regex = "1"
futures = "0.3"
mongodb = { version = "3.2.5", features = ["socks5-proxy"] }
percent-encoding = "2"
diff --git a/src-tauri/src/commands/list_sql_files.rs b/src-tauri/src/commands/list_sql_files.rs
index eedc3709d9..2b0dc58cf1 100644
--- a/src-tauri/src/commands/list_sql_files.rs
+++ b/src-tauri/src/commands/list_sql_files.rs
@@ -1,8 +1,10 @@
+use regex::Regex;
use serde::Serialize;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
const MAX_SCAN_DEPTH: usize = 10;
+const DEFAULT_FILE_FILTER: &str = "*.sql";
/// Directories that are never interesting for SQL file browsing but are huge
/// (often tens of thousands of entries), which makes a recursive scan take
@@ -91,7 +93,50 @@ fn is_pruned_dir(name: &str) -> bool {
PRUNED_DIRS.iter().any(|d| name.eq_ignore_ascii_case(d))
}
-fn scan_sql_files(dir: &Path, depth: usize, visited: &mut HashSet<String>) -> Vec<SqlFileEntry> {
+fn glob_to_regex(glob: &str) -> String {
+ let mut pattern = String::from("(?i)^");
+ for character in glob.chars() {
+ match character {
+ '*' => pattern.push_str(".*"),
+ '?' => pattern.push('.'),
+ _ => pattern.push_str(&regex::escape(&character.to_string())),
+ }
+ }
+ pattern.push('$');
+ pattern
+}
+
+fn is_glob_filter(file_filter: &str) -> bool {
+ let characters: Vec<char> = file_filter.chars().collect();
+ if !characters.contains(&'*') && !characters.contains(&'?') {
+ return false;
+ }
+ for (index, character) in characters.iter().enumerate() {
+ if matches!(character, '\\' | '(' | ')' | '[' | ']' | '{' | '}' | '^' | '$' | '|' | '+') {
+ return false;
+ }
+ // A wildcard directly after `.` is a regex quantifier (`.*`, `.?`),
+ // not a glob wildcard: `.*sql` must stay a regex while `*.sql` is a glob.
+ if matches!(character, '*' | '?') && index > 0 && characters[index - 1] == '.' {
+ return false;
+ }
+ }
+ true
+}
+
+fn compile_file_filter(file_filter: &str) -> Result<Regex, String> {
+ let file_filter = file_filter.trim();
+ let pattern = if file_filter.is_empty() {
+ glob_to_regex(DEFAULT_FILE_FILTER)
+ } else if is_glob_filter(file_filter) {
+ glob_to_regex(file_filter)
+ } else {
+ file_filter.to_string()
+ };
+ Regex::new(&pattern).map_err(|error| format!("Invalid file filter regular expression: {error}"))
+}
+
+fn scan_sql_files(dir: &Path, depth: usize, visited: &mut HashSet<String>, file_filter: &Regex) -> Vec<SqlFileEntry> {
if depth > MAX_SCAN_DEPTH {
return vec![];
}
@@ -127,13 +172,11 @@ fn scan_sql_files(dir: &Path, depth: usize, visited: &mut HashSet<String>) -> Ve
if is_pruned_dir(&name) {
continue;
}
- let children = scan_sql_files(&path, depth + 1, visited);
+ let children = scan_sql_files(&path, depth + 1, visited, file_filter);
if !children.is_empty() {
entries.push(SqlFileEntry { name, path: path.to_string_lossy().to_string(), is_dir: true, children });
}
- } else if file_type.is_file()
- && path.extension().and_then(|e| e.to_str()).map(|e| e.eq_ignore_ascii_case("sql")).unwrap_or(false)
- {
+ } else if file_type.is_file() && file_filter.is_match(&name) {
entries.push(SqlFileEntry {
name,
path: path.to_string_lossy().to_string(),
@@ -155,8 +198,12 @@ fn scan_sql_files(dir: &Path, depth: usize, visited: &mut HashSet<String>) -> Ve
}
#[tauri::command]
-pub async fn list_sql_files_in_folder(folder_path: String) -> Result<Vec<SqlFileEntry>, String> {
+pub async fn list_sql_files_in_folder(
+ folder_path: String,
+ file_filter: Option<String>,
+) -> Result<Vec<SqlFileEntry>, String> {
let path = Path::new(&folder_path).to_path_buf();
+ let file_filter = compile_file_filter(file_filter.as_deref().unwrap_or(DEFAULT_FILE_FILTER))?;
// Filesystem scanning is blocking work; run it on a thread pool so the
// Tauri main thread (and thus the webview) does not freeze while large
// folders are being walked.
@@ -165,7 +212,7 @@ pub async fn list_sql_files_in_folder(folder_path: String) -> Result<Vec<SqlFile
return Err(format!("Path is not a directory: {}", folder_path));
}
let mut visited = HashSet::new();
- Ok(scan_sql_files(&path, 0, &mut visited))
+ Ok(scan_sql_files(&path, 0, &mut visited, &file_filter))
})
.await
.map_err(|e| format!("Failed to scan folder: {e}"))?
@@ -257,7 +304,8 @@ mod tests {
std::fs::write(idea.join("workspace.sql"), "SELECT 3;").unwrap();
let mut visited = HashSet::new();
- let entries = scan_sql_files(&root, 0, &mut visited);
+ let filter = compile_file_filter(DEFAULT_FILE_FILTER).unwrap();
+ let entries = scan_sql_files(&root, 0, &mut visited, &filter);
let mut names = Vec::new();
collect_file_names(&entries, &mut names);
names.sort();
@@ -266,6 +314,53 @@ mod tests {
std::fs::remove_dir_all(root).unwrap();
}
+ #[test]
+ fn scan_sql_files_accepts_user_regular_expressions() {
+ let root = std::env::temp_dir().join(format!("dbx-file-folder-scan-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&root).unwrap();
+ std::fs::write(root.join("query.sql"), "SELECT 1;").unwrap();
+ std::fs::write(root.join("script.sh"), "echo hello").unwrap();
+ std::fs::write(root.join("tool.py"), "print('hello')").unwrap();
+
+ let mut visited = HashSet::new();
+ let filter = compile_file_filter(r"\.(sql|sh|py)$").unwrap();
+ let entries = scan_sql_files(&root, 0, &mut visited, &filter);
+ let mut names = Vec::new();
+ collect_file_names(&entries, &mut names);
+ names.sort();
+
+ assert_eq!(names, vec!["query.sql", "script.sh", "tool.py"]);
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
+ #[test]
+ fn compile_file_filter_accepts_glob_patterns() {
+ let filter = compile_file_filter("*.sh").unwrap();
+
+ assert!(filter.is_match("script.sh"));
+ assert!(filter.is_match("SCRIPT.SH"));
+ assert!(!filter.is_match("script.py"));
+ }
+
+ #[test]
+ fn compile_file_filter_keeps_dot_prefixed_wildcards_as_regex() {
+ // `.*sql` is a regex ("anything ending in sql"), not a glob that would
+ // match only literal dots before "sql".
+ let filter = compile_file_filter(".*sql").unwrap();
+
+ assert!(filter.is_match("notes.sql"));
+ assert!(filter.is_match("mysql-dump.txt"));
+ assert!(!filter.is_match("readme.txt"));
+ }
+
+ #[test]
+ fn compile_file_filter_accepts_question_mark_globs() {
+ let filter = compile_file_filter("file?.sql").unwrap();
+
+ assert!(filter.is_match("file1.sql"));
+ assert!(!filter.is_match("file12.sql"));
+ }
+
#[test]
fn validates_single_sql_file_names() {
assert_eq!(validate_sql_file_name("query.sql").unwrap(), "query.sql");