feat(search): open database search as a tab
This commit is contained in:
1 parent
fdb8e37a48
commit
03fc00c33c
28 files changed
+1062
-367
No files matched your search
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user