feat(search): open database search as a tab

This commit is contained in:
lxk955 authored and GitHub committed 2026-10-02 23:47:55 +08:00
1 parent fdb8e37a48
commit 03fc00c33c
28 files changed
+1062 -367

No files matched your search

+1
View File
@@ -4521,6 +4521,7 @@ onUnmounted(() => {
});
}
"
@open-database-search-target="(_tabId: string, target: any) => openDatabaseSearchTarget(target)"
@object-schema-change="(tabId: string, schema: string | undefined) => queryStore.updateSchema(tabId, schema)"
@object-browser-viewport-change="(tabId: string, viewport: any) => queryStore.updateObjectBrowserViewport(tabId, viewport)"
@object-browser-search-change="(tabId: string, query: string) => queryStore.updateObjectBrowserSearch(tabId, query)"
@@ -123,6 +123,7 @@ const NacosAdminConsole = defineAsyncComponent(() => import("@/components/nacos/
const NacosAccessControlConsole = defineAsyncComponent(() => import("@/components/nacos/NacosAccessControlConsole.vue"));
const NacosDashboard = defineAsyncComponent(() => import("@/components/nacos/NacosDashboard.vue"));
const DoltVersionControl = defineAsyncComponent(() => import("@/components/dolt/DoltVersionControl.vue"));
const DatabaseSearchPanel = defineAsyncComponent(() => import("@/components/search/DatabaseSearchPanel.vue"));
const DatabaseBrowser = defineAsyncComponent(() => import("@/components/objects/DatabaseBrowser.vue"));
const ObjectBrowser = defineAsyncComponent(() => import("@/components/objects/ObjectBrowser.vue"));
const TableStructureEditor = defineAsyncComponent(() => import("@/components/structure/TableStructureEditor.vue"));
@@ -361,6 +362,7 @@ const etcdDashboardRef = ref<{ refresh?: () => boolean }>();
const zookeeperKeyBrowserRef = ref<SearchableBrowserHandle>();
const consulOverviewRef = ref<{ refresh?: () => boolean }>();
const consulWorkspaceRef = ref<SearchableBrowserHandle>();
const databaseSearchPanelRef = ref<{ focusSearch: () => boolean }>();
const databaseBrowserRef = ref<SearchableBrowserHandle>();
const objectBrowserRef = ref<SearchableBrowserHandle>();
const pluginFilesystemTabRef = ref<{ refresh: () => Promise<unknown> }>();
@@ -1258,6 +1260,7 @@ function focusSearch(target: Element | null = null): boolean {
if (props.activeTab.mode === "zookeeper") return zookeeperKeyBrowserRef.value?.focusSearch() ?? false;
if (props.activeTab.mode === "consul") return consulWorkspaceRef.value?.focusSearch() ?? false;
if (props.activeTab.mode === "databases") return databaseBrowserRef.value?.focusSearch() ?? false;
if (props.activeTab.mode === "database-search") return databaseSearchPanelRef.value?.focusSearch() ?? false;
if (props.activeTab.mode === "objects") return objectBrowserRef.value?.focusSearch(target) ?? false;
if (props.activeTab.mode === "structure") return tableStructureEditorRef.value?.focusSearch() ?? false;
if (props.activeTab.mode === "query") {
@@ -3171,6 +3174,26 @@ defineExpose({
/>
</div>
</template>
<!-- Database Search mode -->
<template v-else-if="activeTab.mode === 'database-search'">
<div class="min-w-0 flex-1 min-h-0">
<DatabaseSearchPanel
ref="databaseSearchPanelRef"
:key="activeTab.id"
:connection-id="activeTab.connectionId"
:database="activeTab.database"
:schema="activeTab.schema"
:initial-state="activeTab.databaseSearchState"
@update:state="
(state) => {
activeTab.databaseSearchState = state;
queryStore.updateDatabaseSearchState(activeTab.id, state);
}
"
@open-target="(target) => emit('openDatabaseSearchTarget', activeTab.id, target)"
/>
</div>
</template>
<template v-else-if="activeTab.mode === 'databases' && activeConnection">
<div class="min-w-0 flex-1 min-h-0">
<DatabaseBrowser ref="databaseBrowserRef" :key="activeTab.id" :connection="activeConnection" />
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { Activity, AlertTriangle, Braces, CalendarClock, Clock, Code2, Database, Eye, FileCode, Gauge, KeyRound, Link2, ListTree, Network, Package, PencilRuler, ScrollText, ShieldCheck, Table, TableProperties, UsersRound, Zap } from "@lucide/vue";
import { Activity, AlertTriangle, Braces, CalendarClock, Clock, Code2, Database, Eye, FileCode, Gauge, KeyRound, Link2, ListTree, Network, Package, PencilRuler, ScrollText, Search, ShieldCheck, Table, TableProperties, UsersRound, Zap } from "@lucide/vue";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import PluginIcon from "@/components/plugins/PluginIcon.vue";
import { isEventObjectBrowserTab, tabDatabaseIconType } from "@/lib/tabs/tabPresentation";
@@ -26,6 +26,7 @@ defineProps<{ tab: QueryTab }>();
<TableProperties v-else-if="tab.mode === 'objects'" />
<UsersRound v-else-if="tab.mode === 'users'" />
<PencilRuler v-else-if="tab.mode === 'structure'" />
<Search v-else-if="tab.mode === 'database-search'" />
<ScrollText v-else-if="tab.objectSource?.objectType === 'PROCEDURE'" />
<Braces v-else-if="tab.objectSource?.objectType === 'FUNCTION'" />
<Zap v-else-if="tab.objectSource?.objectType === 'TRIGGER'" />
@@ -1,4 +1,5 @@
import type { ConnectionConfig, ObjectBrowserFilter, ObjectBrowserViewport, QueryTab, TabOutputView } from "@/types/database";
import type { NavigationTarget } from "@/composables/useNavigationTargets";
import type { DataGridReloadIntent } from "@/lib/dataGrid/dataGridToolbar";
import type { DataGridSortMode } from "@/lib/dataGrid/dataGridSort";
import type { SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation";
@@ -101,6 +102,7 @@ export interface ContentAreaSurfaceEmits {
editTableStructure: [tabId: string, target: SqlObjectNavigationTarget];
openObjectSource: [tabId: string, target: SqlObjectNavigationTarget, initialEditing: boolean];
openObjectTable: [tabId: string, target: { tableName: string; schema?: string; tableType?: string; catalog?: string; comment?: string | null }];
openDatabaseSearchTarget: [tabId: string, target: NavigationTarget];
objectSchemaChange: [tabId: string, schema: string | undefined];
objectBrowserViewportChange: [tabId: string, viewport: ObjectBrowserViewport];
objectBrowserSearchChange: [tabId: string, query: string];
@@ -1,19 +1,15 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { uuid } from "@/lib/common/utils";
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import { AlertCircle, Loader2, Search, Square, Table2 } from "@lucide/vue";
import { ExternalLink, Search } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogFooter, DialogHeader, DialogScrollContent, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import DatabaseSearchPanel from "@/components/search/DatabaseSearchPanel.vue";
import { useConnectionStore } from "@/stores/connectionStore";
import * as api from "@/lib/backend/api";
import { buildDatabaseSearchSql, buildSearchResultWhere, findMatchedSearchColumns } from "@/lib/database/databaseSearch";
import { databaseSearchBatchRange, databaseSearchNextBatchSize } from "@/lib/database/databaseSearchBatch";
import type { DatabaseType, TableInfo } from "@/types/database";
import { isSchemaAware } from "@/lib/database/databaseCapabilities";
import { useQueryStore } from "@/stores/queryStore";
import type { DatabaseSearchTabState } from "@/types/database";
import type { NavigationTarget } from "@/composables/useNavigationTargets";
const props = defineProps<{
open: boolean;
@@ -24,284 +20,32 @@ const props = defineProps<{
const emit = defineEmits<{
"update:open": [value: boolean];
"open-target": [
value: {
connectionId: string;
database: string;
schema?: string;
tableName: string;
tableType?: string;
whereInput?: string;
},
];
"open-target": [value: NavigationTarget];
}>();
const { t } = useI18n();
const connectionStore = useConnectionStore();
const queryStore = useQueryStore();
const dialogOpen = computed({
get: () => props.open,
set: (value) => emit("update:open", value),
});
type SearchResultItem = {
id: string;
schema?: string;
tableName: string;
tableType?: string;
matchedColumns: string[];
preview: string;
whereInput: string;
};
type SearchTableTask = {
schema?: string;
table: TableInfo;
};
const SYSTEM_SCHEMAS = new Set(["information_schema", "pg_catalog", "sys", "system", "mysql", "performance_schema", "xdb", "outln", "dbsnmp"]);
const keyword = ref("");
const perTableLimit = ref(20);
const running = ref(false);
const cancelled = ref(false);
const loadingTables = ref(false);
const progressDone = ref(0);
const progressTotal = ref(0);
const results = ref<SearchResultItem[]>([]);
const tableErrors = ref<Array<{ tableName: string; message: string }>>([]);
const generalError = ref("");
const currentExecutionId = ref("");
const tableTasks = ref<SearchTableTask[]>([]);
const nextTableIndex = ref(0);
const activeKeyword = ref("");
const activePerTableLimit = ref(20);
let runId = 0;
const connection = computed(() => (props.prefillConnectionId ? connectionStore.getConfig(props.prefillConnectionId) : undefined));
const scopeLabel = computed(() => [connection.value?.name, props.prefillDatabase, props.prefillSchema].filter(Boolean).join(" / "));
const canSearch = computed(() => Boolean(props.prefillConnectionId && props.prefillDatabase && keyword.value.trim() && !running.value));
const progressLabel = computed(() => t("databaseSearch.progress", { done: progressDone.value, total: progressTotal.value }));
const remainingTableCount = computed(() => Math.max(0, tableTasks.value.length - nextTableIndex.value));
const nextBatchSize = computed(() => databaseSearchNextBatchSize(nextTableIndex.value, tableTasks.value.length));
const canContinueSearch = computed(() => !running.value && !loadingTables.value && remainingTableCount.value > 0);
watch(
dialogOpen,
(open) => {
if (open) {
resetSearchState();
} else {
stopSearch();
}
},
{ immediate: true },
);
const currentState = ref<DatabaseSearchTabState | undefined>(undefined);
const panelRef = ref<InstanceType<typeof DatabaseSearchPanel> | null>(null);
function resetSearchState() {
running.value = false;
cancelled.value = false;
loadingTables.value = false;
progressDone.value = 0;
progressTotal.value = 0;
results.value = [];
tableErrors.value = [];
generalError.value = "";
currentExecutionId.value = "";
tableTasks.value = [];
nextTableIndex.value = 0;
activeKeyword.value = "";
activePerTableLimit.value = 20;
function onStateUpdate(state: DatabaseSearchTabState) {
currentState.value = state;
}
function isSearchableTable(table: TableInfo): boolean {
const type = table.table_type.toUpperCase();
return type.includes("TABLE") && !type.includes("VIEW");
}
function filterSearchSchemas(schemas: string[]): string[] {
return schemas.filter((schema) => !SYSTEM_SCHEMAS.has(schema.toLowerCase()));
}
function makeExecutionId(): string {
if (typeof crypto !== "undefined" && "randomUUID" in crypto) return `database-search-${uuid()}`;
return `database-search-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function valuePreview(value: unknown): string {
if (value === null || value === undefined) return "NULL";
const text = String(value).replace(/\s+/g, " ").trim();
return text.length > 90 ? `${text.slice(0, 90)}...` : text;
}
function rowPreview(columns: string[], row: unknown[], matchedColumns: string[]): string {
const matched = matchedColumns
.slice(0, 3)
.map((column) => {
const index = columns.findIndex((name) => name.toLowerCase() === column.toLowerCase());
return index >= 0 ? `${column}: ${valuePreview(row[index])}` : "";
})
.filter(Boolean);
if (matched.length) return matched.join(" · ");
return columns
.slice(0, 3)
.map((column, index) => `${column}: ${valuePreview(row[index])}`)
.join(" · ");
}
async function listSearchTables(): Promise<SearchTableTask[]> {
if (!connection.value || !props.prefillConnectionId || !props.prefillDatabase) return [];
const databaseType = connection.value.db_type;
const schemaNames = props.prefillSchema ? [props.prefillSchema] : isSchemaAware(databaseType) ? filterSearchSchemas(await api.listSchemas(props.prefillConnectionId, props.prefillDatabase)) : [props.prefillDatabase];
const tasks: SearchTableTask[] = [];
for (const schema of schemaNames) {
const tables = await api.listTables(props.prefillConnectionId, props.prefillDatabase, schema);
for (const table of tables.filter(isSearchableTable)) {
tasks.push({ schema, table });
}
}
return tasks;
}
async function startSearch() {
if (!canSearch.value || !connection.value) return;
const currentRun = ++runId;
resetSearchState();
running.value = true;
loadingTables.value = true;
activeKeyword.value = keyword.value.trim();
activePerTableLimit.value = Math.min(100, Math.max(1, Math.trunc(Number(perTableLimit.value) || 20)));
try {
await connectionStore.ensureConnected(props.prefillConnectionId);
tableTasks.value = await listSearchTables();
if (currentRun !== runId || cancelled.value) return;
progressTotal.value = tableTasks.value.length;
loadingTables.value = false;
await scanTableRange(currentRun, false);
} catch (error: any) {
if (currentRun === runId && !cancelled.value) generalError.value = error?.message || String(error);
} finally {
if (currentRun === runId) {
running.value = false;
loadingTables.value = false;
currentExecutionId.value = "";
}
}
}
async function continueSearch(scanAllRemaining: boolean) {
if (!canContinueSearch.value || !connection.value) return;
const currentRun = ++runId;
cancelled.value = false;
running.value = true;
generalError.value = "";
try {
await connectionStore.ensureConnected(props.prefillConnectionId);
await scanTableRange(currentRun, scanAllRemaining);
} catch (error: any) {
if (currentRun === runId && !cancelled.value) generalError.value = error?.message || String(error);
} finally {
if (currentRun === runId) {
running.value = false;
currentExecutionId.value = "";
}
}
}
async function scanTableRange(currentRun: number, scanAllRemaining: boolean) {
const range = databaseSearchBatchRange(nextTableIndex.value, tableTasks.value.length, scanAllRemaining);
while (nextTableIndex.value < range.end) {
if (currentRun !== runId || cancelled.value) break;
const task = tableTasks.value[nextTableIndex.value];
if (!task) break;
await searchTable(task, connection.value!.db_type, currentRun);
if (currentRun !== runId || cancelled.value) break;
nextTableIndex.value += 1;
progressDone.value = nextTableIndex.value;
}
}
async function searchTable(task: SearchTableTask, databaseType: DatabaseType, currentRun: number) {
const tableLabel = task.schema ? `${task.schema}.${task.table.name}` : task.table.name;
try {
const schema = task.schema || props.prefillDatabase;
const columns = await api.getColumns(props.prefillConnectionId, props.prefillDatabase, schema, task.table.name);
const query = await buildDatabaseSearchSql({
databaseType,
driverProfile: connection.value?.driver_profile,
schema: task.schema,
tableName: task.table.name,
columns,
term: activeKeyword.value,
limit: activePerTableLimit.value,
});
if (!query || currentRun !== runId || cancelled.value) return;
const executionId = makeExecutionId();
currentExecutionId.value = executionId;
const result = await api.executeQuery(props.prefillConnectionId, props.prefillDatabase, query.sql, undefined, executionId);
if (currentExecutionId.value === executionId) currentExecutionId.value = "";
if (currentRun !== runId || cancelled.value) return;
const tableResults: SearchResultItem[] = [];
for (const [rowIndex, row] of result.rows.entries()) {
const matchedColumns = findMatchedSearchColumns(result.columns, row, columns, activeKeyword.value);
const whereInput = await buildSearchResultWhere({
databaseType,
columns,
resultColumns: result.columns,
row,
matchedColumns,
});
if (currentRun !== runId || cancelled.value) return;
tableResults.push({
id: `${tableLabel}:${rowIndex}`,
schema: task.schema,
tableName: task.table.name,
tableType: task.table.table_type,
matchedColumns,
preview: rowPreview(result.columns, row, matchedColumns),
whereInput,
});
}
if (currentRun === runId && !cancelled.value) results.value.push(...tableResults);
} catch (error: any) {
if (currentRun === runId && !cancelled.value) {
tableErrors.value.push({ tableName: tableLabel, message: error?.message || String(error) });
}
}
}
async function stopSearch() {
cancelled.value = true;
runId++;
running.value = false;
loadingTables.value = false;
const executionId = currentExecutionId.value;
currentExecutionId.value = "";
if (executionId) {
try {
await api.cancelQuery(executionId);
} catch {
// Best effort; some drivers may finish before cancellation arrives.
}
}
}
function openResult(item: SearchResultItem) {
emit("open-target", {
connectionId: props.prefillConnectionId,
database: props.prefillDatabase,
schema: item.schema,
tableName: item.tableName,
tableType: item.tableType,
whereInput: item.whereInput,
});
function openInTab() {
const state = currentState.value ?? panelRef.value?.getCurrentState();
dialogOpen.value = false;
queryStore.openDatabaseSearch(props.prefillConnectionId, props.prefillDatabase, props.prefillSchema, state);
}
</script>
@@ -309,96 +53,26 @@ function openResult(item: SearchResultItem) {
<Dialog v-model:open="dialogOpen">
<DialogScrollContent class="flex max-h-[calc(var(--dbx-viewport-height)-6rem)] min-h-0 max-w-4xl flex-col overflow-hidden gap-0 p-0">
<DialogHeader class="shrink-0 border-b px-5 py-4">
<DialogTitle class="flex items-center gap-2">
<Search class="h-5 w-5" />
{{ t("databaseSearch.title") }}
</DialogTitle>
<div class="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<span>{{ scopeLabel }}</span>
<Badge v-if="props.prefillSchema" variant="secondary">{{ props.prefillSchema }}</Badge>
<div class="flex items-center justify-between pr-8">
<div>
<DialogTitle class="flex items-center gap-2">
<Search class="h-5 w-5" />
{{ t("databaseSearch.title") }}
</DialogTitle>
<div class="flex flex-wrap items-center gap-2 text-xs text-muted-foreground mt-1">
<span>{{ scopeLabel }}</span>
<Badge v-if="props.prefillSchema" variant="secondary">{{ props.prefillSchema }}</Badge>
</div>
</div>
<Button variant="outline" size="sm" class="gap-1.5 text-xs shrink-0" @click="openInTab">
<ExternalLink class="h-3.5 w-3.5" />
{{ t("databaseSearch.openInTab") }}
</Button>
</div>
</DialogHeader>
<!-- Keep the actions reachable while the search form and results share the available viewport. -->
<div class="min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4">
<div class="grid gap-3 md:grid-cols-[1fr_9rem_auto]">
<div class="space-y-1.5">
<Label class="text-xs">{{ t("databaseSearch.keyword") }}</Label>
<Input v-model="keyword" class="h-9" :placeholder="t('databaseSearch.keywordPlaceholder')" :disabled="running" @keydown.enter.prevent="startSearch" />
</div>
<div class="space-y-1.5">
<Label class="text-xs">{{ t("databaseSearch.limitPerTable") }}</Label>
<Input v-model.number="perTableLimit" class="h-9" type="number" min="1" max="100" :disabled="running" />
</div>
<div class="flex items-end gap-2">
<Button class="h-9" :disabled="!canSearch" @click="startSearch">
<Loader2 v-if="running" class="h-4 w-4 animate-spin" />
<Search v-else class="h-4 w-4" />
{{ running ? t("databaseSearch.searching") : t("databaseSearch.search") }}
</Button>
<Button v-if="running" variant="destructive" class="h-9" @click="stopSearch">
<Square class="h-4 w-4 fill-current" />
{{ t("databaseSearch.stop") }}
</Button>
</div>
</div>
<div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">
{{ t("databaseSearch.hint") }}
</div>
<div v-if="running || progressTotal" class="flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
<span class="tabular-nums">{{ loadingTables ? t("databaseSearch.loadingTables") : progressLabel }}</span>
<span class="tabular-nums">{{ t("databaseSearch.resultCount", { count: results.length }) }}</span>
<div v-if="canContinueSearch" class="ml-auto flex flex-wrap items-center gap-2">
<Button variant="outline" size="sm" class="h-7 text-xs" @click="continueSearch(false)">
{{ t("databaseSearch.continueNextBatch", { count: nextBatchSize }) }}
</Button>
<Button variant="secondary" size="sm" class="h-7 text-xs" @click="continueSearch(true)">
{{ t("databaseSearch.scanAllRemaining", { count: remainingTableCount }) }}
</Button>
</div>
</div>
<div v-if="generalError" class="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
<AlertCircle class="mt-0.5 h-4 w-4" />
<span>{{ generalError }}</span>
</div>
<div class="space-y-2">
<div class="flex items-center justify-between">
<div class="text-sm font-medium">{{ t("databaseSearch.results") }}</div>
<Badge variant="outline">{{ results.length }}</Badge>
</div>
<div v-if="results.length" class="max-h-[360px] space-y-2 overflow-auto pr-1">
<button v-for="item in results" :key="item.id" class="flex w-full items-start gap-3 rounded-md border bg-background px-3 py-2 text-left hover:bg-muted/40" @click="openResult(item)">
<Table2 class="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<div class="min-w-0 flex-1">
<div class="flex min-w-0 flex-wrap items-center gap-2">
<span class="truncate font-medium">{{ item.schema ? `${item.schema}.${item.tableName}` : item.tableName }}</span>
<Badge v-for="column in item.matchedColumns" :key="column" variant="secondary">{{ column }}</Badge>
</div>
<div class="mt-1 truncate text-xs text-muted-foreground">{{ item.preview }}</div>
</div>
<span class="shrink-0 text-xs text-primary">{{ t("databaseSearch.openResult") }}</span>
</button>
</div>
<div v-else class="rounded-md border border-dashed py-10 text-center text-sm text-muted-foreground">
{{ running ? t("databaseSearch.waiting") : t("databaseSearch.noResults") }}
</div>
</div>
<div v-if="tableErrors.length" class="space-y-2">
<div class="text-sm font-medium text-muted-foreground">
{{ t("databaseSearch.errors") }}
</div>
<div class="max-h-24 space-y-1 overflow-auto rounded-md border bg-muted/20 p-2 text-xs text-muted-foreground">
<div v-for="error in tableErrors" :key="`${error.tableName}:${error.message}`">
<span class="font-medium text-foreground">{{ error.tableName }}</span
>: {{ error.message }}
</div>
</div>
</div>
<div class="min-h-0 flex-1 overflow-y-auto px-5 py-4">
<DatabaseSearchPanel ref="panelRef" :connection-id="props.prefillConnectionId" :database="props.prefillDatabase" :schema="props.prefillSchema" :in-dialog="true" @update:state="onStateUpdate" @open-target="emit('open-target', $event)" @open-in-tab="openInTab" />
</div>
<DialogFooter class="shrink-0 border-t px-5 py-3">
@@ -0,0 +1,468 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { uuid } from "@/lib/common/utils";
import { useI18n } from "vue-i18n";
import { AlertCircle, Loader2, Search, Square, Table2 } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useConnectionStore } from "@/stores/connectionStore";
import * as api from "@/lib/backend/api";
import { buildDatabaseSearchSql, buildSearchResultWhere, findMatchedSearchColumns } from "@/lib/database/databaseSearch";
import { databaseSearchBatchRange, databaseSearchNextBatchSize } from "@/lib/database/databaseSearchBatch";
import type { DatabaseSearchResultItem, DatabaseSearchTableTask, DatabaseSearchTabState, DatabaseType, TableInfo } from "@/types/database";
import type { NavigationTarget } from "@/composables/useNavigationTargets";
import { isSchemaAware } from "@/lib/database/databaseCapabilities";
const props = withDefaults(
defineProps<{
connectionId: string;
database: string;
schema?: string;
initialState?: DatabaseSearchTabState;
inDialog?: boolean;
}>(),
{
schema: undefined,
initialState: undefined,
inDialog: false,
},
);
const emit = defineEmits<{
"update:state": [state: DatabaseSearchTabState];
"open-target": [value: NavigationTarget];
"open-in-tab": [];
}>();
const { t } = useI18n();
const connectionStore = useConnectionStore();
const SYSTEM_SCHEMAS = new Set(["information_schema", "pg_catalog", "sys", "system", "mysql", "performance_schema", "xdb", "outln", "dbsnmp"]);
const keywordInputRef = ref<any>(null);
const keyword = ref(props.initialState?.keyword ?? "");
const perTableLimit = ref(props.initialState?.perTableLimit ?? 20);
const running = ref(false);
const cancelled = ref(false);
const loadingTables = ref(false);
const progressDone = ref(props.initialState?.progressDone ?? 0);
const progressTotal = ref(props.initialState?.progressTotal ?? 0);
const results = ref<DatabaseSearchResultItem[]>(props.initialState?.results ? [...props.initialState.results] : []);
const tableErrors = ref<Array<{ tableName: string; message: string }>>(props.initialState?.tableErrors ? [...props.initialState.tableErrors] : []);
const generalError = ref(props.initialState?.generalError ?? "");
const currentExecutionId = ref("");
const tableTasks = ref<DatabaseSearchTableTask[]>(props.initialState?.tableTasks ? [...props.initialState.tableTasks] : []);
const nextTableIndex = ref(props.initialState?.nextTableIndex ?? 0);
const activeKeyword = ref(props.initialState?.activeKeyword ?? "");
const activePerTableLimit = ref(props.initialState?.activePerTableLimit ?? 20);
let runId = 0;
const connection = computed(() => (props.connectionId ? connectionStore.getConfig(props.connectionId) : undefined));
const scopeLabel = computed(() => [connection.value?.name, props.database, props.schema].filter(Boolean).join(" / "));
const canSearch = computed(() => Boolean(props.connectionId && props.database && keyword.value.trim() && !running.value));
const progressLabel = computed(() => t("databaseSearch.progress", { done: progressDone.value, total: progressTotal.value }));
const remainingTableCount = computed(() => Math.max(0, tableTasks.value.length - nextTableIndex.value));
const nextBatchSize = computed(() => databaseSearchNextBatchSize(nextTableIndex.value, tableTasks.value.length));
const canContinueSearch = computed(() => !running.value && !loadingTables.value && remainingTableCount.value > 0);
function getCurrentState(): DatabaseSearchTabState {
return {
keyword: keyword.value,
perTableLimit: perTableLimit.value,
results: results.value,
tableErrors: tableErrors.value,
generalError: generalError.value,
tableTasks: tableTasks.value,
nextTableIndex: nextTableIndex.value,
activeKeyword: activeKeyword.value,
activePerTableLimit: activePerTableLimit.value,
progressDone: progressDone.value,
progressTotal: progressTotal.value,
};
}
function emitState() {
emit("update:state", getCurrentState());
}
watch([keyword, perTableLimit], () => {
emitState();
});
watch(
() => props.initialState,
(incoming) => {
if (!incoming || running.value) return;
if (incoming.keyword !== undefined && incoming.keyword !== keyword.value) keyword.value = incoming.keyword;
if (incoming.perTableLimit !== undefined && incoming.perTableLimit !== perTableLimit.value) perTableLimit.value = incoming.perTableLimit;
if (incoming.results) results.value = [...incoming.results];
if (incoming.tableErrors) tableErrors.value = [...incoming.tableErrors];
if (incoming.generalError !== undefined) generalError.value = incoming.generalError;
if (incoming.tableTasks) tableTasks.value = [...incoming.tableTasks];
if (incoming.nextTableIndex !== undefined) nextTableIndex.value = incoming.nextTableIndex;
if (incoming.activeKeyword !== undefined) activeKeyword.value = incoming.activeKeyword;
if (incoming.activePerTableLimit !== undefined) activePerTableLimit.value = incoming.activePerTableLimit;
if (incoming.progressDone !== undefined) progressDone.value = incoming.progressDone;
if (incoming.progressTotal !== undefined) progressTotal.value = incoming.progressTotal;
},
{ deep: true },
);
function resetSearchState() {
running.value = false;
cancelled.value = false;
loadingTables.value = false;
progressDone.value = 0;
progressTotal.value = 0;
results.value = [];
tableErrors.value = [];
generalError.value = "";
currentExecutionId.value = "";
tableTasks.value = [];
nextTableIndex.value = 0;
activeKeyword.value = "";
activePerTableLimit.value = 20;
emitState();
}
function isSearchableTable(table: TableInfo): boolean {
const type = table.table_type.toUpperCase();
return type.includes("TABLE") && !type.includes("VIEW");
}
function filterSearchSchemas(schemas: string[]): string[] {
return schemas.filter((schema) => !SYSTEM_SCHEMAS.has(schema.toLowerCase()));
}
function makeExecutionId(): string {
if (typeof crypto !== "undefined" && "randomUUID" in crypto) return `database-search-${uuid()}`;
return `database-search-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function valuePreview(value: unknown): string {
if (value === null || value === undefined) return "NULL";
const text = String(value).replace(/\s+/g, " ").trim();
return text.length > 90 ? `${text.slice(0, 90)}...` : text;
}
function rowPreview(columns: string[], row: unknown[], matchedColumns: string[]): string {
const matched = matchedColumns
.slice(0, 3)
.map((column) => {
const index = columns.findIndex((name) => name.toLowerCase() === column.toLowerCase());
return index >= 0 ? `${column}: ${valuePreview(row[index])}` : "";
})
.filter(Boolean);
if (matched.length) return matched.join(" · ");
return columns
.slice(0, 3)
.map((column, index) => `${column}: ${valuePreview(row[index])}`)
.join(" · ");
}
async function listSearchTables(): Promise<DatabaseSearchTableTask[]> {
if (!connection.value || !props.connectionId || !props.database) return [];
const databaseType = connection.value.db_type;
const schemaNames = props.schema ? [props.schema] : isSchemaAware(databaseType) ? filterSearchSchemas(await api.listSchemas(props.connectionId, props.database)) : [props.database];
const tasks: DatabaseSearchTableTask[] = [];
for (const schema of schemaNames) {
const tables = await api.listTables(props.connectionId, props.database, schema);
for (const table of tables.filter(isSearchableTable)) {
tasks.push({ schema, table });
}
}
return tasks;
}
async function startSearch() {
if (!canSearch.value || !connection.value) return;
const currentRun = ++runId;
resetSearchState();
running.value = true;
loadingTables.value = true;
activeKeyword.value = keyword.value.trim();
activePerTableLimit.value = Math.min(100, Math.max(1, Math.trunc(Number(perTableLimit.value) || 20)));
emitState();
try {
await connectionStore.ensureConnected(props.connectionId);
tableTasks.value = await listSearchTables();
if (currentRun !== runId || cancelled.value) return;
progressTotal.value = tableTasks.value.length;
loadingTables.value = false;
emitState();
await scanTableRange(currentRun, false);
} catch (error: any) {
if (currentRun === runId && !cancelled.value) {
generalError.value = error?.message || String(error);
emitState();
}
} finally {
if (currentRun === runId) {
running.value = false;
loadingTables.value = false;
currentExecutionId.value = "";
emitState();
}
}
}
async function continueSearch(scanAllRemaining: boolean) {
if (!canContinueSearch.value || !connection.value) return;
const currentRun = ++runId;
cancelled.value = false;
running.value = true;
generalError.value = "";
emitState();
try {
await connectionStore.ensureConnected(props.connectionId);
await scanTableRange(currentRun, scanAllRemaining);
} catch (error: any) {
if (currentRun === runId && !cancelled.value) {
generalError.value = error?.message || String(error);
emitState();
}
} finally {
if (currentRun === runId) {
running.value = false;
currentExecutionId.value = "";
emitState();
}
}
}
async function scanTableRange(currentRun: number, scanAllRemaining: boolean) {
const range = databaseSearchBatchRange(nextTableIndex.value, tableTasks.value.length, scanAllRemaining);
while (nextTableIndex.value < range.end) {
if (currentRun !== runId || cancelled.value) break;
const task = tableTasks.value[nextTableIndex.value];
if (!task) break;
await searchTable(task, connection.value!.db_type, currentRun);
if (currentRun !== runId || cancelled.value) break;
nextTableIndex.value += 1;
progressDone.value = nextTableIndex.value;
emitState();
}
}
async function searchTable(task: DatabaseSearchTableTask, databaseType: DatabaseType, currentRun: number) {
const tableLabel = task.schema ? `${task.schema}.${task.table.name}` : task.table.name;
try {
const schema = task.schema || props.database;
const columns = await api.getColumns(props.connectionId, props.database, schema, task.table.name);
const query = await buildDatabaseSearchSql({
databaseType,
driverProfile: connection.value?.driver_profile,
schema: task.schema,
tableName: task.table.name,
columns,
term: activeKeyword.value,
limit: activePerTableLimit.value,
});
if (!query || currentRun !== runId || cancelled.value) return;
const executionId = makeExecutionId();
currentExecutionId.value = executionId;
const result = await api.executeQuery(props.connectionId, props.database, query.sql, undefined, executionId);
if (currentExecutionId.value === executionId) currentExecutionId.value = "";
if (currentRun !== runId || cancelled.value) return;
const tableResults: DatabaseSearchResultItem[] = [];
for (const [rowIndex, row] of result.rows.entries()) {
const matchedColumns = findMatchedSearchColumns(result.columns, row, columns, activeKeyword.value);
const whereInput = await buildSearchResultWhere({
databaseType,
columns,
resultColumns: result.columns,
row,
matchedColumns,
});
if (currentRun !== runId || cancelled.value) return;
tableResults.push({
id: `${tableLabel}:${rowIndex}`,
schema: task.schema,
tableName: task.table.name,
tableType: task.table.table_type,
matchedColumns,
preview: rowPreview(result.columns, row, matchedColumns),
whereInput,
});
}
if (currentRun === runId && !cancelled.value) {
results.value.push(...tableResults);
emitState();
}
} catch (error: any) {
if (currentRun === runId && !cancelled.value) {
tableErrors.value.push({ tableName: tableLabel, message: error?.message || String(error) });
emitState();
}
}
}
async function stopSearch() {
cancelled.value = true;
runId++;
running.value = false;
loadingTables.value = false;
const executionId = currentExecutionId.value;
currentExecutionId.value = "";
emitState();
if (executionId) {
try {
await api.cancelQuery(executionId);
} catch {
// Best effort; some drivers may finish before cancellation arrives.
}
}
}
function openResult(item: DatabaseSearchResultItem) {
emit("open-target", {
connectionId: props.connectionId,
database: props.database,
schema: item.schema,
tableName: item.tableName,
tableType: item.tableType,
whereInput: item.whereInput,
});
}
function focusSearch(): boolean {
if (keywordInputRef.value) {
const el = "$el" in keywordInputRef.value ? keywordInputRef.value.$el : keywordInputRef.value;
el?.focus?.();
return true;
}
return false;
}
onMounted(() => {
emitState();
});
onBeforeUnmount(() => {
if (running.value) {
void stopSearch();
}
emitState();
});
defineExpose({
focusSearch,
stopSearch,
resetSearchState,
startSearch,
continueSearch,
getCurrentState,
});
</script>
<template>
<div :class="['flex min-h-0 flex-col', inDialog ? 'space-y-4' : 'h-full bg-background']">
<!-- Header for standalone Tab mode -->
<div v-if="!inDialog" class="flex shrink-0 items-center justify-between border-b px-5 py-3 bg-muted/10">
<div class="flex items-center gap-2">
<Search class="h-5 w-5 text-muted-foreground" />
<span class="font-medium text-sm">{{ t("databaseSearch.title") }}</span>
<div class="flex flex-wrap items-center gap-2 text-xs text-muted-foreground ml-3">
<span>{{ scopeLabel }}</span>
<Badge v-if="props.schema" variant="secondary">{{ props.schema }}</Badge>
</div>
</div>
<div class="flex items-center gap-2">
<Badge v-if="results.length" variant="outline">{{ t("databaseSearch.resultCount", { count: results.length }) }}</Badge>
</div>
</div>
<!-- Main search container -->
<div :class="['min-h-0 flex-1 flex flex-col overflow-y-auto space-y-4', inDialog ? '' : 'p-5']">
<div class="grid gap-3 md:grid-cols-[1fr_9rem_auto] shrink-0">
<div class="space-y-1.5">
<Label class="text-xs">{{ t("databaseSearch.keyword") }}</Label>
<Input ref="keywordInputRef" v-model="keyword" class="h-9" :placeholder="t('databaseSearch.keywordPlaceholder')" :disabled="running" @keydown.enter.prevent="startSearch" />
</div>
<div class="space-y-1.5">
<Label class="text-xs">{{ t("databaseSearch.limitPerTable") }}</Label>
<Input v-model.number="perTableLimit" class="h-9" type="number" min="1" max="100" :disabled="running" />
</div>
<div class="flex items-end gap-2">
<Button class="h-9" :disabled="!canSearch" @click="startSearch">
<Loader2 v-if="running" class="h-4 w-4 animate-spin" />
<Search v-else class="h-4 w-4" />
{{ running ? t("databaseSearch.searching") : t("databaseSearch.search") }}
</Button>
<Button v-if="running" variant="destructive" class="h-9" @click="stopSearch">
<Square class="h-4 w-4 fill-current" />
{{ t("databaseSearch.stop") }}
</Button>
</div>
</div>
<div class="rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground shrink-0">
{{ t("databaseSearch.hint") }}
</div>
<div v-if="running || progressTotal" class="flex flex-wrap items-center gap-3 text-xs text-muted-foreground shrink-0">
<span class="tabular-nums">{{ loadingTables ? t("databaseSearch.loadingTables") : progressLabel }}</span>
<span class="tabular-nums">{{ t("databaseSearch.resultCount", { count: results.length }) }}</span>
<div v-if="canContinueSearch" class="ml-auto flex flex-wrap items-center gap-2">
<Button variant="outline" size="sm" class="h-7 text-xs" @click="continueSearch(false)">
{{ t("databaseSearch.continueNextBatch", { count: nextBatchSize }) }}
</Button>
<Button variant="secondary" size="sm" class="h-7 text-xs" @click="continueSearch(true)">
{{ t("databaseSearch.scanAllRemaining", { count: remainingTableCount }) }}
</Button>
</div>
</div>
<div v-if="generalError" class="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive shrink-0">
<AlertCircle class="mt-0.5 h-4 w-4" />
<span>{{ generalError }}</span>
</div>
<div :class="['space-y-2 flex flex-col', inDialog ? '' : 'flex-1 min-h-0']">
<div class="flex items-center justify-between shrink-0">
<div class="text-sm font-medium">{{ t("databaseSearch.results") }}</div>
<Badge variant="outline">{{ results.length }}</Badge>
</div>
<div v-if="results.length" :class="['space-y-2 overflow-y-auto pr-1', inDialog ? 'max-h-[360px]' : 'flex-1 min-h-0']">
<button v-for="item in results" :key="item.id" class="flex w-full items-start gap-3 rounded-md border bg-background px-3 py-2 text-left hover:bg-muted/40 transition-colors" @click="openResult(item)">
<Table2 class="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<div class="min-w-0 flex-1">
<div class="flex min-w-0 flex-wrap items-center gap-2">
<span class="truncate font-medium">{{ item.schema ? `${item.schema}.${item.tableName}` : item.tableName }}</span>
<Badge v-for="column in item.matchedColumns" :key="column" variant="secondary">{{ column }}</Badge>
</div>
<div class="mt-1 truncate text-xs text-muted-foreground">{{ item.preview }}</div>
</div>
<span class="shrink-0 text-xs text-primary font-medium">{{ t("databaseSearch.openResult") }}</span>
</button>
</div>
<div v-else class="rounded-md border border-dashed py-10 text-center text-sm text-muted-foreground">
{{ running ? t("databaseSearch.waiting") : t("databaseSearch.noResults") }}
</div>
</div>
<div v-if="tableErrors.length" class="space-y-2 shrink-0">
<div class="text-sm font-medium text-muted-foreground">
{{ t("databaseSearch.errors") }}
</div>
<div class="max-h-24 space-y-1 overflow-auto rounded-md border bg-muted/20 p-2 text-xs text-muted-foreground">
<div v-for="error in tableErrors" :key="`${error.tableName}:${error.message}`">
<span class="font-medium text-foreground">{{ error.tableName }}</span
>: {{ error.message }}
</div>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,250 @@
// @vitest-environment happy-dom
import { createApp, defineComponent, h, nextTick, ref, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createPinia, setActivePinia } from "pinia";
import i18n from "@/i18n";
import type { DatabaseSearchResultItem, DatabaseSearchTabState } from "@/types/database";
import type { NavigationTarget } from "@/composables/useNavigationTargets";
vi.mock("@/components/ui/dialog", async () => {
const { defineComponent, h } = await import("vue");
const passthrough = defineComponent({
setup(_props, { slots }) {
return () => h("div", slots.default?.());
},
});
const dialog = defineComponent({
props: { open: Boolean },
emits: ["update:open"],
setup(props, { slots }) {
return () => (props.open ? h("div", slots.default?.()) : null);
},
});
return {
Dialog: dialog,
DialogScrollContent: passthrough,
DialogContent: passthrough,
DialogFooter: passthrough,
DialogHeader: passthrough,
DialogTitle: passthrough,
};
});
vi.mock("@/components/ui/button", async () => {
const { defineComponent, h } = await import("vue");
return {
Button: defineComponent({
props: { disabled: Boolean, variant: String, size: String },
emits: ["click"],
setup(props, { slots, emit }) {
return () =>
h(
"button",
{
disabled: props.disabled,
onClick: (e: MouseEvent) => emit("click", e),
},
slots.default?.(),
);
},
}),
};
});
vi.mock("@/components/ui/input", async () => {
const { defineComponent, h } = await import("vue");
return {
Input: defineComponent({
props: { modelValue: [String, Number], disabled: Boolean, placeholder: String, type: String },
emits: ["update:modelValue", "keydown"],
setup(props, { emit }) {
return () =>
h("input", {
value: props.modelValue,
disabled: props.disabled,
placeholder: props.placeholder,
type: props.type || "text",
onInput: (e: any) => emit("update:modelValue", e.target.value),
onKeydown: (e: any) => emit("keydown", e),
});
},
}),
};
});
vi.mock("@/components/ui/badge", async () => {
const { defineComponent, h } = await import("vue");
return {
Badge: defineComponent({
setup(_props, { slots }) {
return () => h("span", slots.default?.());
},
}),
};
});
vi.mock("@/components/ui/label", async () => {
const { defineComponent, h } = await import("vue");
return {
Label: defineComponent({
setup(_props, { slots }) {
return () => h("label", slots.default?.());
},
}),
};
});
import DatabaseSearchPanel from "@/components/search/DatabaseSearchPanel.vue";
import DatabaseSearchDialog from "@/components/search/DatabaseSearchDialog.vue";
import { useQueryStore } from "@/stores/queryStore";
const mountedApps: App[] = [];
beforeEach(() => {
setActivePinia(createPinia());
});
afterEach(() => {
for (const app of mountedApps.splice(0)) app.unmount();
document.body.innerHTML = "";
});
describe("DatabaseSearchPanel", () => {
it("restores search results and keyword from initialState", async () => {
const initialState: DatabaseSearchTabState = {
keyword: "admin_user",
perTableLimit: 30,
progressDone: 3,
progressTotal: 10,
results: [
{
id: "users:0",
tableName: "users",
schema: "public",
matchedColumns: ["username"],
preview: "username: admin_user",
whereInput: "\"username\" = 'admin_user'",
},
],
};
let emittedTarget: NavigationTarget | null = null;
const container = document.createElement("div");
document.body.append(container);
const app = createApp(
defineComponent({
setup() {
return () =>
h(DatabaseSearchPanel, {
connectionId: "conn-1",
database: "shop",
schema: "public",
initialState,
inDialog: false,
"onOpen-target": (target: NavigationTarget) => {
emittedTarget = target;
},
});
},
}),
);
app.use(i18n);
mountedApps.push(app);
app.mount(container);
await nextTick();
const input = container.querySelector("input") as HTMLInputElement;
expect(input.value).toBe("admin_user");
const resultButtons = container.querySelectorAll("button");
const resultItemBtn = Array.from(resultButtons).find((btn) => btn.textContent?.includes("users"));
expect(resultItemBtn).toBeDefined();
resultItemBtn?.click();
await nextTick();
expect(emittedTarget).toMatchObject({
connectionId: "conn-1",
database: "shop",
schema: "public",
tableName: "users",
whereInput: "\"username\" = 'admin_user'",
});
});
it("updates and emits state when inputs change", async () => {
let latestState: DatabaseSearchTabState | null = null;
const container = document.createElement("div");
document.body.append(container);
const app = createApp(
defineComponent({
setup() {
return () =>
h(DatabaseSearchPanel, {
connectionId: "conn-1",
database: "shop",
"onUpdate:state": (state: DatabaseSearchTabState) => {
latestState = state;
},
});
},
}),
);
app.use(i18n);
mountedApps.push(app);
app.mount(container);
await nextTick();
const input = container.querySelector("input") as HTMLInputElement;
input.value = "new_search";
input.dispatchEvent(new Event("input"));
await nextTick();
expect(latestState?.keyword).toBe("new_search");
});
});
describe("DatabaseSearchDialog", () => {
it("opens in tab when openInTab is clicked and transfers search state", async () => {
const queryStore = useQueryStore();
const openSpy = vi.spyOn(queryStore, "openDatabaseSearch");
let open = true;
const container = document.createElement("div");
document.body.append(container);
const app = createApp(
defineComponent({
setup() {
return () =>
h(DatabaseSearchDialog, {
open,
prefillConnectionId: "conn-1",
prefillDatabase: "testdb",
prefillSchema: "public",
"onUpdate:open": (v: boolean) => {
open = v;
},
});
},
}),
);
app.use(i18n);
mountedApps.push(app);
app.mount(container);
await nextTick();
const buttons = Array.from(container.querySelectorAll("button"));
const openInTabBtn = buttons.find((btn) => btn.textContent?.includes("Open in Tab") || btn.textContent?.includes("页签") || btn.textContent?.includes("分頁"));
expect(openInTabBtn).toBeDefined();
openInTabBtn?.click();
await nextTick();
expect(openSpy).toHaveBeenCalledWith("conn-1", "testdb", "public", expect.any(Object));
expect(open).toBe(false);
});
});
@@ -121,11 +121,7 @@ export function useSidebarTreeToolRuntime(options: SidebarTreeToolRuntimeOptions
function openDatabaseSearch() {
const node = activeNode.value;
if (!node.connectionId || !node.database) return;
connectionStore.databaseSearchSource = {
connectionId: node.connectionId,
database: node.database,
schema: node.type === "schema" ? node.schema : undefined,
};
queryStore.openDatabaseSearch(node.connectionId, node.database, node.type === "schema" ? node.schema : undefined);
}
function openDatabaseExport() {
+1
View File
@@ -2870,6 +2870,7 @@ export default withEnglishFallback({
scanAllRemaining: "Qalan {count} cədvəli skan et",
results: "Nəticələr",
openResult: "Aç",
openInTab: "Vərəqdə aç",
waiting: "Uyğunluqlar gözlənilir...",
noResults: "Hələ uyğunluq yoxdur",
errors: "Bəzi cədvəllərdə əməliyyat uğursuz oldu",
+1
View File
@@ -3253,6 +3253,7 @@ export default {
scanAllRemaining: "Scan remaining {count}",
results: "Results",
openResult: "Open",
openInTab: "Open in Tab",
waiting: "Waiting for matches...",
noResults: "No matches yet",
errors: "Some tables failed",
+1
View File
@@ -3210,6 +3210,7 @@ export default withEnglishFallback({
scanAllRemaining: "Analizar las {count} restantes",
results: "Resultados",
openResult: "Abrir",
openInTab: "Abrir en pestaña",
waiting: "Esperando coincidencias...",
noResults: "Sin coincidencias aún",
errors: "Algunas tablas fallaron",
+1
View File
@@ -3157,6 +3157,7 @@ export default withEnglishFallback({
scanAllRemaining: "Pindai {count} sisanya",
results: "Hasil",
openResult: "Buka",
openInTab: "Buka di Tab",
waiting: "Menunggu kecocokan...",
noResults: "Belum ada kecocokan",
errors: "Beberapa tabel gagal",
+1
View File
@@ -3064,6 +3064,7 @@ export default withEnglishFallback({
scanAllRemaining: "Scansiona le {count} rimanenti",
results: "Risultati",
openResult: "Apri",
openInTab: "Apri in scheda",
waiting: "In attesa di corrispondenze...",
noResults: "Nessuna corrispondenza finora",
errors: "Alcune tabelle non sono riuscite",
+1
View File
@@ -3090,6 +3090,7 @@ export default withEnglishFallback({
scanAllRemaining: "残り{count}テーブルをスキャン",
results: "結果",
openResult: "開く",
openInTab: "タブで開く",
waiting: "一致を待機中...",
noResults: "一致する結果はまだありません",
errors: "一部のテーブルで失敗しました",
+1
View File
@@ -2972,6 +2972,7 @@ export default withEnglishFallback({
scanAllRemaining: "남은 {count}개 스캔",
results: "결과",
openResult: "열기",
openInTab: "탭으로 열기",
waiting: "일치 항목을 기다리는 중...",
noResults: "아직 일치 항목이 없습니다",
errors: "일부 테이블이 실패했습니다",
+1
View File
@@ -3066,6 +3066,7 @@ export default withEnglishFallback({
scanAllRemaining: "Verificar {count} restantes",
results: "Resultados",
openResult: "Abrir",
openInTab: "Abrir em aba",
waiting: "Aguardando correspondências...",
noResults: "Nenhuma correspondência ainda",
errors: "Algumas tabelas falharam",
+1
View File
@@ -3108,6 +3108,7 @@ export default withEnglishFallback({
scanAllRemaining: "Просканировать оставшиеся {count}",
results: "Результаты",
openResult: "Открыть",
openInTab: "Открыть во вкладке",
waiting: "Ожидание совпадений...",
noResults: "Пока нет совпадений",
errors: "Сбой при обработке некоторых таблиц",
+1
View File
@@ -2848,6 +2848,7 @@ export default withEnglishFallback({
scanAllRemaining: "Kalan {count} tanesini tara",
results: "Sonuçlar",
openResult: "Aç",
openInTab: "Sekmede Aç",
waiting: "Eşleşmeler bekleniyor...",
noResults: "Henüz eşleşme yok",
errors: "Bazı tablolar başarısız oldu",
+1
View File
@@ -3165,6 +3165,7 @@ export default withEnglishFallback({
scanAllRemaining: "扫描剩余 {count} 张",
results: "查找结果",
openResult: "打开",
openInTab: "以页签方式打开",
waiting: "等待命中结果...",
noResults: "暂无命中结果",
errors: "部分表查找失败",
+1
View File
@@ -3063,6 +3063,7 @@ export default withEnglishFallback({
scanAllRemaining: "掃描剩餘 {count} 張",
results: "搜尋結果",
openResult: "開啟",
openInTab: "以分頁方式開啟",
waiting: "搜尋中……",
noResults: "暫無搜尋結果",
errors: "部分資料表搜尋失敗",
@@ -295,6 +295,53 @@ describe("openTabsPersistence originalSql round-trip", () => {
currentUri: "s3://bucket/reports/",
});
});
it("preserves database-search tab state across a round-trip", () => {
const [restored] = roundTrip([
queryTab({
id: "search-tab",
title: "Search Database",
connectionId: "conn-1",
database: "shop",
schema: "public",
mode: "database-search",
databaseSearchState: {
keyword: "order_123",
perTableLimit: 25,
progressDone: 4,
progressTotal: 8,
results: [
{
id: "orders:0",
tableName: "orders",
schema: "public",
matchedColumns: ["order_no"],
preview: "order_no: order_123",
whereInput: "\"order_no\" = 'order_123'",
},
],
},
}),
]);
expect(restored.mode).toBe("database-search");
expect(restored.databaseSearchState).toEqual({
keyword: "order_123",
perTableLimit: 25,
progressDone: 4,
progressTotal: 8,
results: [
{
id: "orders:0",
tableName: "orders",
schema: "public",
matchedColumns: ["order_no"],
preview: "order_no: order_123",
whereInput: "\"order_no\" = 'order_123'",
},
],
});
});
});
describe("openTabsPersistence detached connection tabs", () => {
@@ -21,6 +21,7 @@ import {
tabDisplayTitles,
syncTabTitleNumbers,
tabIconClass,
tabModeLabel,
tabTooltipLines,
tabularResultItems,
dirtyTabTitleStyle,
@@ -37,6 +38,7 @@ const translations: Record<string, string> = {
"tree.events": "Events",
"connectionGroup.ungroupedLabel": "Ungrouped",
"editor.noDatabase": "No database",
"databaseSearch.title": "Search Database",
};
const translate = (key: string) => translations[key] ?? key;
@@ -474,6 +476,17 @@ describe("tab group presentation", () => {
expect(tabDisplayTitle(queryTab({ mode: "objects", objectBrowser: { objectType: "tables", initialObjectFilter: "events" } }), translate)).toBe("Events@db");
});
it("formats database-search tab titles with database and schema scope", () => {
expect(tabDisplayTitle(queryTab({ mode: "database-search", database: "shop", schema: "public" }), translate)).toBe("Search Database@shop.public");
expect(tabDisplayTitle(queryTab({ mode: "database-search", database: "shop" }), translate)).toBe("Search Database@shop");
expect(tabModeLabel(queryTab({ mode: "database-search" }), translate)).toBe("Search Database");
const settings = useSettingsStore();
settings.editorSettings.compactTabTitle = true;
expect(tabDisplayTitle(queryTab({ mode: "database-search", database: "shop" }), translate)).toBe("Search Database");
settings.editorSettings.compactTabTitle = false;
});
it("uses the live database and branch context for Dolt version control tabs", () => {
const store = useConnectionStore();
store.connections = [{ id: "conn-1", name: "Production Dolt", db_type: "mysql", driver_profile: "dolt", database: "app" } as ConnectionConfig];
@@ -65,6 +65,7 @@ export interface SavedOpenTab {
nacosNamespaceName?: string;
structureTableName?: string;
structureDraft?: QueryTab["structureDraft"];
databaseSearchState?: QueryTab["databaseSearchState"];
objectBrowser?: QueryTab["objectBrowser"];
objectSource?: QueryTab["objectSource"];
sourceView?: boolean;
@@ -212,6 +213,7 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
...(tab.nacosNamespaceName !== undefined ? { nacosNamespaceName: tab.nacosNamespaceName } : {}),
...(tab.structureTableName !== undefined ? { structureTableName: tab.structureTableName } : {}),
...(tab.structureDraft ? { structureDraft: JSON.parse(JSON.stringify(tab.structureDraft)) } : {}),
...(tab.databaseSearchState ? { databaseSearchState: tab.databaseSearchState } : {}),
objectBrowser: tab.objectBrowser,
objectSource: tab.objectSource,
...(tab.sourceView ? { sourceView: true } : {}),
@@ -34,6 +34,7 @@ export const contentSurfaceEventNames = [
"editTableStructure",
"openObjectSource",
"openObjectTable",
"openDatabaseSearchTarget",
"objectSchemaChange",
"objectBrowserViewportChange",
"objectBrowserSearchChange",
@@ -287,6 +287,11 @@ export function tabDisplayTitle(tab: QueryTab, t: Translate): string {
if (compact) return t("tabs.users");
return `${t("tabs.users")}@${connectionDisplayName(tab.connectionId)}`;
}
if (tab.mode === "database-search") {
const scope = tab.schema ? `${database}.${tab.schema}` : database;
if (compact) return t("databaseSearch.title");
return `${t("databaseSearch.title")}@${scope}`;
}
return tab.title;
}
@@ -677,6 +682,7 @@ export function tabModeLabel(tab: QueryTab, t: Translate): string {
if (tab.mode === "objects") return t("tabs.objects");
if (tab.mode === "users") return t("tabs.users");
if (tab.mode === "dolt-version-control") return t("doltVersionControl.title");
if (tab.mode === "database-search") return t("databaseSearch.title");
return tab.mode;
}
@@ -0,0 +1,129 @@
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DatabaseSearchTabState } from "@/types/database";
function installLocalStorage() {
const data = new Map<string, string>();
vi.stubGlobal("localStorage", {
getItem: vi.fn((key: string) => data.get(key) ?? null),
setItem: vi.fn((key: string, value: string) => data.set(key, value)),
removeItem: vi.fn((key: string) => data.delete(key)),
});
return data;
}
const QUERY_STORE_TEST_TIMEOUT = 30_000;
describe("queryStore database-search tabs", () => {
beforeEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
installLocalStorage();
setActivePinia(createPinia());
}, QUERY_STORE_TEST_TIMEOUT);
it(
"opens a new database-search tab with initial state",
async () => {
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const initialState: DatabaseSearchTabState = {
keyword: "test_keyword",
perTableLimit: 50,
progressDone: 5,
progressTotal: 10,
results: [
{
id: "users:0",
tableName: "users",
matchedColumns: ["email"],
preview: "email: test@example.com",
whereInput: "\"email\" = 'test@example.com'",
},
],
};
const tabId = store.openDatabaseSearch("conn-1", "mydb", "public", initialState);
expect(store.tabs).toHaveLength(1);
const tab = store.tabs.find((t) => t.id === tabId);
expect(tab).toBeDefined();
expect(tab?.mode).toBe("database-search");
expect(tab?.connectionId).toBe("conn-1");
expect(tab?.database).toBe("mydb");
expect(tab?.schema).toBe("public");
expect(tab?.databaseSearchState).toMatchObject(initialState);
expect(store.activeTabId).toBe(tabId);
},
QUERY_STORE_TEST_TIMEOUT,
);
it(
"reuses an existing database-search tab and merges incoming state",
async () => {
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const firstId = store.openDatabaseSearch("conn-1", "mydb", "public", {
keyword: "first",
});
const secondId = store.openDatabaseSearch("conn-1", "mydb", "public", {
keyword: "updated",
perTableLimit: 30,
});
expect(secondId).toBe(firstId);
expect(store.tabs).toHaveLength(1);
const tab = store.tabs.find((t) => t.id === firstId);
expect(tab?.databaseSearchState?.keyword).toBe("updated");
expect(tab?.databaseSearchState?.perTableLimit).toBe(30);
},
QUERY_STORE_TEST_TIMEOUT,
);
it(
"opens distinct tabs for different databases or schemas",
async () => {
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const id1 = store.openDatabaseSearch("conn-1", "mydb", "public");
const id2 = store.openDatabaseSearch("conn-1", "mydb", "private");
const id3 = store.openDatabaseSearch("conn-1", "otherdb");
expect(store.tabs).toHaveLength(3);
expect(id1).not.toBe(id2);
expect(id2).not.toBe(id3);
},
QUERY_STORE_TEST_TIMEOUT,
);
it(
"updates tab databaseSearchState via updateDatabaseSearchState",
async () => {
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.openDatabaseSearch("conn-1", "mydb");
const tab = store.tabs.find((t) => t.id === tabId)!;
expect(tab.databaseSearchState).toBeUndefined();
const nextState: DatabaseSearchTabState = {
keyword: "users",
perTableLimit: 25,
results: [],
tableErrors: [],
generalError: "",
progressDone: 10,
progressTotal: 20,
};
store.updateDatabaseSearchState(tabId, nextState);
expect(tab.databaseSearchState).toMatchObject(nextState);
},
QUERY_STORE_TEST_TIMEOUT,
);
});
+39
View File
@@ -14,6 +14,7 @@ import type {
BatchSqlExecution,
BatchStatementExecutionItem,
ConnectionConfig,
DatabaseSearchTabState,
DatabaseType,
IndexInfo,
NacosConfigEditorViewport,
@@ -3318,6 +3319,36 @@ export const useQueryStore = defineStore("query", () => {
return registerOpenTab(tab);
}
function openDatabaseSearch(connectionId: string, database: string, schema?: string, initialState?: DatabaseSearchTabState) {
const existing = tabs.value.find((tab) => tab.mode === "database-search" && tab.connectionId === connectionId && tab.database === database && (tab.schema || "") === (schema || ""));
if (existing) {
if (initialState) {
existing.databaseSearchState = {
...existing.databaseSearchState,
...initialState,
};
}
switchTab(existing.id);
return existing.id;
}
const id = uuid();
const tab: QueryTab = {
id,
title: "Database Search",
connectionId,
database,
schema,
sql: "",
isExecuting: false,
isCancelling: false,
isExplaining: false,
mode: "database-search",
databaseSearchState: initialState,
};
return registerOpenTab(tab);
}
function openDatabaseBrowser(connectionId: string) {
const existing = tabs.value.find((tab) => tab.mode === "databases" && tab.connectionId === connectionId);
if (existing) {
@@ -5333,6 +5364,12 @@ export const useQueryStore = defineStore("query", () => {
tab.objectBrowser = { ...tab.objectBrowser, filter };
}
function updateDatabaseSearchState(id: string, state: DatabaseSearchTabState) {
const tab = tabs.value.find((t) => t.id === id);
if (!tab || tab.mode !== "database-search") return;
tab.databaseSearchState = state;
}
function updateNacosConfigEditorViewport(connectionId: string, namespace: string, viewport: NacosConfigEditorViewport) {
if (!Number.isFinite(viewport.scrollTop) || !Number.isFinite(viewport.scrollLeft)) return;
const tab = tabs.value.find((candidate) => candidate.mode === "nacos" && candidate.connectionId === connectionId && (candidate.nacosNamespace || "") === namespace);
@@ -9571,6 +9608,7 @@ export const useQueryStore = defineStore("query", () => {
updateObjectBrowserViewport,
updateObjectBrowserSearch,
updateObjectBrowserFilter,
updateDatabaseSearchState,
updateNacosConfigEditorViewport,
setAutoCommit,
markManualTransactionDirty,
@@ -9579,6 +9617,7 @@ export const useQueryStore = defineStore("query", () => {
ensureManualTransactionSession,
renameTab,
openDatabaseBrowser,
openDatabaseSearch,
openDriverProfileWorkspace,
openObjectBrowser,
openMongoGridFs,
+32 -1
View File
@@ -1896,6 +1896,35 @@ export interface TabUiState {
page?: Record<string, TabPageUiState>;
}
export interface DatabaseSearchResultItem {
id: string;
schema?: string;
tableName: string;
tableType?: string;
matchedColumns: string[];
preview: string;
whereInput: string;
}
export interface DatabaseSearchTableTask {
schema?: string;
table: TableInfo;
}
export interface DatabaseSearchTabState {
keyword: string;
perTableLimit: number;
progressDone: number;
progressTotal: number;
results: DatabaseSearchResultItem[];
tableErrors: Array<{ tableName: string; message: string }>;
generalError: string;
tableTasks: DatabaseSearchTableTask[];
nextTableIndex: number;
activeKeyword: string;
activePerTableLimit: number;
}
export interface QueryTab {
id: string;
/** Stable creation time used when tabs are displayed in creation order. */
@@ -2066,7 +2095,8 @@ export interface QueryTab {
| "solr-admin"
| "dolt-version-control"
| "plugin-workbench"
| "plugin-filesystem";
| "plugin-filesystem"
| "database-search";
pluginWorkbench?: {
/** Host command that created this tab; distinct commands can share a workbench. */
commandId?: string;
@@ -2099,6 +2129,7 @@ export interface QueryTab {
structureInitialTabRequestId?: number;
structureInitialTarget?: TableStructureEditorTarget;
structureDraft?: TableStructureEditorDraft;
databaseSearchState?: DatabaseSearchTabState;
objectBrowser?: {
catalog?: string;
schema?: string;