feat(desktop): add connection-level database browser
This commit is contained in:
46 files changed
+781
-29
No files matched your search
@@ -2,7 +2,7 @@
|
|||||||
import { computed, ref, watch, nextTick, onUnmounted } from "vue";
|
import { computed, ref, watch, nextTick, onUnmounted } from "vue";
|
||||||
import type { CSSProperties } from "vue";
|
import type { CSSProperties } from "vue";
|
||||||
import { useI18n } from "vue-i18n";
|
import { useI18n } from "vue-i18n";
|
||||||
import { X, Pin, ChevronDown, Table2, Code2, TableProperties, PencilRuler, KeyRound, Pencil, Package, Lock, Copy, AlertTriangle, Network, Minimize2, Maximize2, Settings, CalendarClock, Activity, Gauge, ShieldCheck } from "@lucide/vue";
|
import { X, Pin, ChevronDown, Table2, Code2, TableProperties, PencilRuler, KeyRound, Pencil, Package, Lock, Copy, AlertTriangle, Network, Minimize2, Maximize2, Settings, CalendarClock, Activity, Gauge, ShieldCheck, Database } from "@lucide/vue";
|
||||||
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
|
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
|
||||||
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
|
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||||
@@ -494,7 +494,7 @@ function tabColorStyle(tab: QueryTab) {
|
|||||||
function tabIconClass(tab: QueryTab) {
|
function tabIconClass(tab: QueryTab) {
|
||||||
if (tab.externalSqlFileMissing) return "text-amber-600 dark:text-amber-400";
|
if (tab.externalSqlFileMissing) return "text-amber-600 dark:text-amber-400";
|
||||||
if (tab.mode === "mq") return "";
|
if (tab.mode === "mq") return "";
|
||||||
if (tab.mode === "objects") return "text-amber-500 dark:text-amber-400";
|
if (tab.mode === "databases" || tab.mode === "objects") return "text-amber-500 dark:text-amber-400";
|
||||||
if (tab.mode === "data" || tab.mode === "mongo" || tab.mode === "vector" || tab.mode === "redis" || tab.mode === "hbase" || tab.mode === "structure") return "text-emerald-600 dark:text-emerald-400";
|
if (tab.mode === "data" || tab.mode === "mongo" || tab.mode === "vector" || tab.mode === "redis" || tab.mode === "hbase" || tab.mode === "structure") return "text-emerald-600 dark:text-emerald-400";
|
||||||
return "text-blue-600 dark:text-blue-400";
|
return "text-blue-600 dark:text-blue-400";
|
||||||
}
|
}
|
||||||
@@ -530,6 +530,7 @@ function tabMenuIcon(tab: QueryTab) {
|
|||||||
if (tab.mode === "etcd-dashboard") return Gauge;
|
if (tab.mode === "etcd-dashboard") return Gauge;
|
||||||
if (tab.mode === "etcd-access-control") return ShieldCheck;
|
if (tab.mode === "etcd-access-control") return ShieldCheck;
|
||||||
if (tab.mode === "nacos") return Network;
|
if (tab.mode === "nacos") return Network;
|
||||||
|
if (tab.mode === "databases") return Database;
|
||||||
if (tab.mode === "objects") return TableProperties;
|
if (tab.mode === "objects") return TableProperties;
|
||||||
if (tab.mode === "structure") return PencilRuler;
|
if (tab.mode === "structure") return PencilRuler;
|
||||||
if (tab.mode === "dameng-jobs") return CalendarClock;
|
if (tab.mode === "dameng-jobs") return CalendarClock;
|
||||||
@@ -677,6 +678,7 @@ function onOverflowItemKeydown(event: KeyboardEvent, tabId: string, kind: "regul
|
|||||||
<Gauge v-else-if="tab.mode === 'etcd-dashboard'" class="h-3.5 w-3.5" />
|
<Gauge v-else-if="tab.mode === 'etcd-dashboard'" class="h-3.5 w-3.5" />
|
||||||
<ShieldCheck v-else-if="tab.mode === 'etcd-access-control'" class="h-3.5 w-3.5" />
|
<ShieldCheck v-else-if="tab.mode === 'etcd-access-control'" class="h-3.5 w-3.5" />
|
||||||
<Network v-else-if="tab.mode === 'nacos'" class="h-3.5 w-3.5" />
|
<Network v-else-if="tab.mode === 'nacos'" class="h-3.5 w-3.5" />
|
||||||
|
<Database v-else-if="tab.mode === 'databases'" class="h-3.5 w-3.5" />
|
||||||
<TableProperties v-else-if="tab.mode === 'objects'" class="h-3.5 w-3.5" />
|
<TableProperties v-else-if="tab.mode === 'objects'" class="h-3.5 w-3.5" />
|
||||||
<PencilRuler v-else-if="tab.mode === 'structure'" class="h-3.5 w-3.5" />
|
<PencilRuler v-else-if="tab.mode === 'structure'" class="h-3.5 w-3.5" />
|
||||||
<CalendarClock v-else-if="tab.mode === 'dameng-jobs'" class="h-3.5 w-3.5" />
|
<CalendarClock v-else-if="tab.mode === 'dameng-jobs'" class="h-3.5 w-3.5" />
|
||||||
@@ -874,6 +876,7 @@ function onOverflowItemKeydown(event: KeyboardEvent, tabId: string, kind: "regul
|
|||||||
<Gauge v-else-if="tab.mode === 'etcd-dashboard'" class="h-3.5 w-3.5" />
|
<Gauge v-else-if="tab.mode === 'etcd-dashboard'" class="h-3.5 w-3.5" />
|
||||||
<ShieldCheck v-else-if="tab.mode === 'etcd-access-control'" class="h-3.5 w-3.5" />
|
<ShieldCheck v-else-if="tab.mode === 'etcd-access-control'" class="h-3.5 w-3.5" />
|
||||||
<Network v-else-if="tab.mode === 'nacos'" class="h-3.5 w-3.5" />
|
<Network v-else-if="tab.mode === 'nacos'" class="h-3.5 w-3.5" />
|
||||||
|
<Database v-else-if="tab.mode === 'databases'" class="h-3.5 w-3.5" />
|
||||||
<TableProperties v-else-if="tab.mode === 'objects'" class="h-3.5 w-3.5" />
|
<TableProperties v-else-if="tab.mode === 'objects'" class="h-3.5 w-3.5" />
|
||||||
<PencilRuler v-else-if="tab.mode === 'structure'" class="h-3.5 w-3.5" />
|
<PencilRuler v-else-if="tab.mode === 'structure'" class="h-3.5 w-3.5" />
|
||||||
<CalendarClock v-else-if="tab.mode === 'dameng-jobs'" class="h-3.5 w-3.5" />
|
<CalendarClock v-else-if="tab.mode === 'dameng-jobs'" class="h-3.5 w-3.5" />
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ const MqAdminConsole = defineAsyncComponent(() => import("@/components/mq/MqAdmi
|
|||||||
const MqttAdminConsole = defineAsyncComponent(() => import("@/components/mqtt/MqttAdminConsole.vue"));
|
const MqttAdminConsole = defineAsyncComponent(() => import("@/components/mqtt/MqttAdminConsole.vue"));
|
||||||
const NacosAdminConsole = defineAsyncComponent(() => import("@/components/nacos/NacosAdminConsole.vue"));
|
const NacosAdminConsole = defineAsyncComponent(() => import("@/components/nacos/NacosAdminConsole.vue"));
|
||||||
const NacosDashboard = defineAsyncComponent(() => import("@/components/nacos/NacosDashboard.vue"));
|
const NacosDashboard = defineAsyncComponent(() => import("@/components/nacos/NacosDashboard.vue"));
|
||||||
|
const DatabaseBrowser = defineAsyncComponent(() => import("@/components/objects/DatabaseBrowser.vue"));
|
||||||
const ObjectBrowser = defineAsyncComponent(() => import("@/components/objects/ObjectBrowser.vue"));
|
const ObjectBrowser = defineAsyncComponent(() => import("@/components/objects/ObjectBrowser.vue"));
|
||||||
const TableStructureEditor = defineAsyncComponent(() => import("@/components/structure/TableStructureEditor.vue"));
|
const TableStructureEditor = defineAsyncComponent(() => import("@/components/structure/TableStructureEditor.vue"));
|
||||||
const DatabaseUserAdmin = defineAsyncComponent(() => import("@/components/admin/DatabaseUserAdmin.vue"));
|
const DatabaseUserAdmin = defineAsyncComponent(() => import("@/components/admin/DatabaseUserAdmin.vue"));
|
||||||
@@ -247,6 +248,7 @@ const etcdDashboardRef = ref<{ refresh?: () => boolean }>();
|
|||||||
const zookeeperKeyBrowserRef = ref<SearchableBrowserHandle>();
|
const zookeeperKeyBrowserRef = ref<SearchableBrowserHandle>();
|
||||||
const consulOverviewRef = ref<{ refresh?: () => boolean }>();
|
const consulOverviewRef = ref<{ refresh?: () => boolean }>();
|
||||||
const consulWorkspaceRef = ref<SearchableBrowserHandle>();
|
const consulWorkspaceRef = ref<SearchableBrowserHandle>();
|
||||||
|
const databaseBrowserRef = ref<SearchableBrowserHandle>();
|
||||||
const objectBrowserRef = ref<SearchableBrowserHandle>();
|
const objectBrowserRef = ref<SearchableBrowserHandle>();
|
||||||
const activeTableMeta = computed(() => props.activeTab.tableMeta);
|
const activeTableMeta = computed(() => props.activeTab.tableMeta);
|
||||||
const activeDataTabTableMeta = computed(() => tableMetaForDataTab(props.activeTab));
|
const activeDataTabTableMeta = computed(() => tableMetaForDataTab(props.activeTab));
|
||||||
@@ -785,6 +787,7 @@ function focusSearch(): boolean {
|
|||||||
if (props.activeTab.mode === "etcd") return etcdKeyBrowserRef.value?.focusSearch() ?? false;
|
if (props.activeTab.mode === "etcd") return etcdKeyBrowserRef.value?.focusSearch() ?? false;
|
||||||
if (props.activeTab.mode === "zookeeper") return zookeeperKeyBrowserRef.value?.focusSearch() ?? false;
|
if (props.activeTab.mode === "zookeeper") return zookeeperKeyBrowserRef.value?.focusSearch() ?? false;
|
||||||
if (props.activeTab.mode === "consul") return consulWorkspaceRef.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 === "objects") return objectBrowserRef.value?.focusSearch() ?? false;
|
if (props.activeTab.mode === "objects") return objectBrowserRef.value?.focusSearch() ?? false;
|
||||||
if (props.activeTab.mode === "query") return queryEditorRef.value?.openSearch() ?? false;
|
if (props.activeTab.mode === "query") return queryEditorRef.value?.openSearch() ?? false;
|
||||||
return dataGridRef.value?.focusSearch() ?? false;
|
return dataGridRef.value?.focusSearch() ?? false;
|
||||||
@@ -804,6 +807,7 @@ function refreshData(): boolean {
|
|||||||
if (props.activeTab.mode === "zookeeper") return zookeeperKeyBrowserRef.value?.refresh?.() ?? false;
|
if (props.activeTab.mode === "zookeeper") return zookeeperKeyBrowserRef.value?.refresh?.() ?? false;
|
||||||
if (props.activeTab.mode === "consul-overview") return consulOverviewRef.value?.refresh?.() ?? false;
|
if (props.activeTab.mode === "consul-overview") return consulOverviewRef.value?.refresh?.() ?? false;
|
||||||
if (props.activeTab.mode === "consul") return consulWorkspaceRef.value?.refresh?.() ?? false;
|
if (props.activeTab.mode === "consul") return consulWorkspaceRef.value?.refresh?.() ?? false;
|
||||||
|
if (props.activeTab.mode === "databases") return databaseBrowserRef.value?.refresh?.() ?? false;
|
||||||
// Restored data tabs intentionally omit row data, so refresh must work before DataGrid mounts.
|
// Restored data tabs intentionally omit row data, so refresh must work before DataGrid mounts.
|
||||||
if (canReloadUnavailableDataTab(props.activeTab)) {
|
if (canReloadUnavailableDataTab(props.activeTab)) {
|
||||||
emit("reload");
|
emit("reload");
|
||||||
@@ -2041,6 +2045,12 @@ defineExpose({ focusSearch, refreshData, refreshQueryEditorCompletionCache, hand
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<template v-else-if="activeTab.mode === 'databases' && activeConnection">
|
||||||
|
<div class="min-w-0 flex-1 min-h-0">
|
||||||
|
<DatabaseBrowser ref="databaseBrowserRef" :connection="activeConnection" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
<!-- Objects mode: virtualized database object browser -->
|
<!-- Objects mode: virtualized database object browser -->
|
||||||
<template v-else-if="activeTab.mode === 'objects' && activeConnection">
|
<template v-else-if="activeTab.mode === 'objects' && activeConnection">
|
||||||
<div class="min-w-0 flex-1 min-h-0">
|
<div class="min-w-0 flex-1 min-h-0">
|
||||||
|
|||||||
@@ -27,10 +27,12 @@ describe("AppTabBar HBase presentation", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("AppTabBar objects presentation", () => {
|
describe("AppTabBar object browser presentation", () => {
|
||||||
it("uses an amber icon color on regular, pinned, and overflow tab surfaces", () => {
|
it("uses matching icons and colors for object and database browser tabs", () => {
|
||||||
expect(tabBarSource).toContain('if (tab.mode === "objects") return "text-amber-500 dark:text-amber-400";');
|
expect(tabBarSource).toContain('if (tab.mode === "databases" || tab.mode === "objects") return "text-amber-500 dark:text-amber-400";');
|
||||||
|
expect(tabBarSource).toContain('if (tab.mode === "databases") return Database;');
|
||||||
expect(tabBarSource).toContain('if (tab.mode === "objects") return TableProperties;');
|
expect(tabBarSource).toContain('if (tab.mode === "objects") return TableProperties;');
|
||||||
|
expect(tabBarSource.match(/tab\.mode === 'databases'/g)).toHaveLength(2);
|
||||||
expect(tabBarSource.match(/:class="tabIconClass\(tab\)"/g)).toHaveLength(2);
|
expect(tabBarSource.match(/:class="tabIconClass\(tab\)"/g)).toHaveLength(2);
|
||||||
expect(tabBarSource.match(/tabMenuIcon\(tab\).*tabIconClass\(tab\)/g)).toHaveLength(2);
|
expect(tabBarSource.match(/tabMenuIcon\(tab\).*tabIconClass\(tab\)/g)).toHaveLength(2);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,334 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||||
|
import { ArrowDown, ArrowUp, Database, GripVertical, LayoutGrid, List, Loader2, RefreshCw, Search } from "@lucide/vue";
|
||||||
|
import { useI18n } from "vue-i18n";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import * as api from "@/lib/backend/api";
|
||||||
|
import { filterDatabaseNamesForConnection } from "@/lib/database/visibleDatabases";
|
||||||
|
import { formatObjectBrowserBytes, formatObjectBrowserTimestamp } from "@/lib/table/objectBrowserRows";
|
||||||
|
import { useQueryStore } from "@/stores/queryStore";
|
||||||
|
import { useSettingsStore } from "@/stores/settingsStore";
|
||||||
|
import type { ConnectionConfig } from "@/types/database";
|
||||||
|
|
||||||
|
type DatabaseRow = {
|
||||||
|
name: string;
|
||||||
|
sizeBytes: number | null;
|
||||||
|
createdAt: string | null;
|
||||||
|
updatedAt: string | null;
|
||||||
|
comment: string | null;
|
||||||
|
defaultCharset: string | null;
|
||||||
|
defaultCollation: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
type DatabaseBrowserColumnKey = "name" | "sizeBytes" | "createdAt" | "updatedAt" | "defaultCharset" | "defaultCollation" | "comment";
|
||||||
|
type DatabaseBrowserSortKey = DatabaseBrowserColumnKey;
|
||||||
|
type SortDirection = "asc" | "desc";
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
connection: ConnectionConfig;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
const settingsStore = useSettingsStore();
|
||||||
|
const searchInput = ref<HTMLInputElement>();
|
||||||
|
const search = ref("");
|
||||||
|
const rows = ref<DatabaseRow[]>([]);
|
||||||
|
const loading = ref(false);
|
||||||
|
const error = ref("");
|
||||||
|
const sortKey = ref<DatabaseBrowserSortKey>("name");
|
||||||
|
const sortDirection = ref<SortDirection>("asc");
|
||||||
|
const columnWidths = ref<Record<DatabaseBrowserColumnKey, number>>({
|
||||||
|
name: 260,
|
||||||
|
sizeBytes: 100,
|
||||||
|
createdAt: 150,
|
||||||
|
updatedAt: 150,
|
||||||
|
defaultCharset: 130,
|
||||||
|
defaultCollation: 170,
|
||||||
|
comment: 260,
|
||||||
|
});
|
||||||
|
let stopColumnResize: (() => void) | null = null;
|
||||||
|
|
||||||
|
const hasSize = computed(() => rows.value.some((row) => row.sizeBytes != null));
|
||||||
|
const hasCreatedAt = computed(() => rows.value.some((row) => !!row.createdAt?.trim()));
|
||||||
|
const hasUpdatedAt = computed(() => rows.value.some((row) => !!row.updatedAt?.trim()));
|
||||||
|
const hasComment = computed(() => rows.value.some((row) => !!row.comment?.trim()));
|
||||||
|
const hasDefaultCharset = computed(() => rows.value.some((row) => !!row.defaultCharset?.trim()));
|
||||||
|
const hasDefaultCollation = computed(() => rows.value.some((row) => !!row.defaultCollation?.trim()));
|
||||||
|
const isListView = computed(() => settingsStore.editorSettings.objectBrowserViewMode !== "grid");
|
||||||
|
|
||||||
|
const columns = computed<DatabaseBrowserColumnKey[]>(() => {
|
||||||
|
const next: DatabaseBrowserColumnKey[] = ["name"];
|
||||||
|
if (hasSize.value) next.push("sizeBytes");
|
||||||
|
if (hasCreatedAt.value) next.push("createdAt");
|
||||||
|
if (hasUpdatedAt.value) next.push("updatedAt");
|
||||||
|
if (hasDefaultCharset.value) next.push("defaultCharset");
|
||||||
|
if (hasDefaultCollation.value) next.push("defaultCollation");
|
||||||
|
if (hasComment.value) next.push("comment");
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
|
||||||
|
const gridTemplateColumns = computed(() => columns.value.map((key, index) => (index === columns.value.length - 1 ? `minmax(${columnWidths.value[key]}px, 1fr)` : `${columnWidths.value[key]}px`)).join(" "));
|
||||||
|
const gridMinWidth = computed(() => columns.value.reduce((total, key) => total + columnWidths.value[key], 0) + Math.max(0, columns.value.length - 1) * 12 + 24);
|
||||||
|
const sortKeyOptions = computed(() => columns.value);
|
||||||
|
|
||||||
|
const visibleRows = computed(() => {
|
||||||
|
const query = search.value.trim().toLocaleLowerCase();
|
||||||
|
const filtered = rows.value.filter((row) => !query || row.name.toLocaleLowerCase().includes(query) || row.comment?.toLocaleLowerCase().includes(query));
|
||||||
|
return [...filtered].sort((left, right) => compareRows(left, right, sortKey.value, sortDirection.value));
|
||||||
|
});
|
||||||
|
|
||||||
|
function openDatabase(database: string) {
|
||||||
|
queryStore.openObjectBrowser(props.connection.id, database);
|
||||||
|
}
|
||||||
|
|
||||||
|
function columnLabel(key: DatabaseBrowserColumnKey): string {
|
||||||
|
if (key === "name") return t("objects.name");
|
||||||
|
if (key === "sizeBytes") return t("objects.size");
|
||||||
|
if (key === "createdAt") return t("objects.createdAt");
|
||||||
|
if (key === "updatedAt") return t("objects.updatedAt");
|
||||||
|
if (key === "defaultCharset") return t("databaseBrowser.defaultCharset");
|
||||||
|
if (key === "defaultCollation") return t("databaseBrowser.defaultCollation");
|
||||||
|
return t("objects.comment");
|
||||||
|
}
|
||||||
|
|
||||||
|
function displayValue(row: DatabaseRow, key: DatabaseBrowserColumnKey): string {
|
||||||
|
if (key === "name") return row.name;
|
||||||
|
if (key === "sizeBytes") return row.sizeBytes == null ? "" : formatObjectBrowserBytes(row.sizeBytes);
|
||||||
|
if (key === "createdAt") return formatObjectBrowserTimestamp(row.createdAt);
|
||||||
|
if (key === "updatedAt") return formatObjectBrowserTimestamp(row.updatedAt);
|
||||||
|
if (key === "defaultCharset") return row.defaultCharset || "";
|
||||||
|
if (key === "defaultCollation") return row.defaultCollation || "";
|
||||||
|
return row.comment || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareRows(left: DatabaseRow, right: DatabaseRow, key: DatabaseBrowserSortKey, direction: SortDirection): number {
|
||||||
|
const leftValue = key === "sizeBytes" ? (left.sizeBytes ?? -1) : displayValue(left, key).toLocaleLowerCase();
|
||||||
|
const rightValue = key === "sizeBytes" ? (right.sizeBytes ?? -1) : displayValue(right, key).toLocaleLowerCase();
|
||||||
|
const compared = typeof leftValue === "number" && typeof rightValue === "number" ? leftValue - rightValue : String(leftValue).localeCompare(String(rightValue), undefined, { numeric: true, sensitivity: "base" });
|
||||||
|
if (compared !== 0) return direction === "asc" ? compared : -compared;
|
||||||
|
return left.name.localeCompare(right.name, undefined, { numeric: true, sensitivity: "base" });
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortIconFor(key: DatabaseBrowserSortKey) {
|
||||||
|
if (sortKey.value !== key) return null;
|
||||||
|
return sortDirection.value === "asc" ? ArrowUp : ArrowDown;
|
||||||
|
}
|
||||||
|
|
||||||
|
function initialSortDirection(key: DatabaseBrowserSortKey): SortDirection {
|
||||||
|
return key === "sizeBytes" || key === "createdAt" || key === "updatedAt" ? "desc" : "asc";
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleSort(key: DatabaseBrowserSortKey) {
|
||||||
|
if (sortKey.value === key) {
|
||||||
|
sortDirection.value = sortDirection.value === "asc" ? "desc" : "asc";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sortKey.value = key;
|
||||||
|
sortDirection.value = initialSortDirection(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setViewMode(mode: "list" | "grid") {
|
||||||
|
settingsStore.updateEditorSettings({ objectBrowserViewMode: mode });
|
||||||
|
}
|
||||||
|
|
||||||
|
function minimumColumnWidth(key: DatabaseBrowserColumnKey): number {
|
||||||
|
return key === "name" || key === "comment" ? 120 : 72;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onColumnResizeStart(key: DatabaseBrowserColumnKey, event: MouseEvent) {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
stopColumnResize?.();
|
||||||
|
const startX = event.clientX;
|
||||||
|
const startWidth = columnWidths.value[key];
|
||||||
|
const minWidth = minimumColumnWidth(key);
|
||||||
|
document.body.classList.add("select-none", "cursor-col-resize");
|
||||||
|
const onMove = (moveEvent: MouseEvent) => {
|
||||||
|
columnWidths.value = { ...columnWidths.value, [key]: Math.max(minWidth, startWidth + moveEvent.clientX - startX) };
|
||||||
|
};
|
||||||
|
const onUp = () => {
|
||||||
|
document.removeEventListener("mousemove", onMove);
|
||||||
|
document.removeEventListener("mouseup", onUp);
|
||||||
|
document.body.classList.remove("select-none", "cursor-col-resize");
|
||||||
|
stopColumnResize = null;
|
||||||
|
};
|
||||||
|
stopColumnResize = onUp;
|
||||||
|
document.addEventListener("mousemove", onMove);
|
||||||
|
document.addEventListener("mouseup", onUp);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetColumnWidth(key: DatabaseBrowserColumnKey, width: number, event: MouseEvent) {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
columnWidths.value = { ...columnWidths.value, [key]: width };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refresh(): Promise<boolean> {
|
||||||
|
loading.value = true;
|
||||||
|
error.value = "";
|
||||||
|
try {
|
||||||
|
let databases;
|
||||||
|
try {
|
||||||
|
databases = await api.listDatabaseMetadata(props.connection.id);
|
||||||
|
} catch (metadataError) {
|
||||||
|
try {
|
||||||
|
databases = await api.listDatabases(props.connection.id);
|
||||||
|
} catch {
|
||||||
|
throw metadataError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const visibleNames = new Set(
|
||||||
|
filterDatabaseNamesForConnection(
|
||||||
|
databases.map((database) => database.name),
|
||||||
|
props.connection,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
rows.value = databases
|
||||||
|
.filter((database) => database.name.trim() && visibleNames.has(database.name))
|
||||||
|
.map((database) => ({
|
||||||
|
name: database.name,
|
||||||
|
sizeBytes: database.size_bytes ?? null,
|
||||||
|
createdAt: database.created_at ?? null,
|
||||||
|
updatedAt: database.updated_at ?? null,
|
||||||
|
comment: database.comment ?? null,
|
||||||
|
defaultCharset: database.default_charset ?? null,
|
||||||
|
defaultCollation: database.default_collation ?? null,
|
||||||
|
}));
|
||||||
|
} catch (cause: any) {
|
||||||
|
rows.value = [];
|
||||||
|
error.value = cause?.message || String(cause);
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function focusSearch(): boolean {
|
||||||
|
searchInput.value?.focus();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(sortKeyOptions, (options) => {
|
||||||
|
if (!options.includes(sortKey.value)) {
|
||||||
|
sortKey.value = "name";
|
||||||
|
sortDirection.value = "asc";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.connection.id,
|
||||||
|
() => {
|
||||||
|
search.value = "";
|
||||||
|
void refresh();
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
onBeforeUnmount(() => stopColumnResize?.());
|
||||||
|
|
||||||
|
defineExpose({ focusSearch, refresh });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="flex h-full min-h-0 min-w-0 flex-col bg-background">
|
||||||
|
<div class="flex h-10 shrink-0 items-center gap-2 border-b px-3">
|
||||||
|
<span class="inline-flex max-w-[14rem] min-w-0 items-center truncate rounded border border-border bg-muted/50 px-2 py-0.5 text-xs font-medium" :title="connection.name">
|
||||||
|
{{ connection.name }}
|
||||||
|
</span>
|
||||||
|
<div class="relative min-w-0 flex-1">
|
||||||
|
<Search class="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||||
|
<Input ref="searchInput" v-model="search" class="h-7 pl-8 text-xs" :placeholder="t('databaseBrowser.search')" />
|
||||||
|
</div>
|
||||||
|
<div class="flex h-7 shrink-0 items-center rounded border bg-muted/20 p-0.5">
|
||||||
|
<select
|
||||||
|
class="h-6 cursor-pointer appearance-none rounded-sm bg-transparent px-1.5 text-xs text-muted-foreground outline-none hover:text-foreground focus:text-foreground"
|
||||||
|
:value="sortKey"
|
||||||
|
:aria-label="t('objects.sortBy')"
|
||||||
|
@change="toggleSort(($event.target as HTMLSelectElement).value as DatabaseBrowserSortKey)"
|
||||||
|
>
|
||||||
|
<option v-for="key in sortKeyOptions" :key="key" :value="key" class="bg-background text-foreground">{{ columnLabel(key) }}</option>
|
||||||
|
</select>
|
||||||
|
<button type="button" class="flex h-6 w-6 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:text-foreground" :title="sortDirection === 'asc' ? t('objects.sortAsc') : t('objects.sortDesc')" @click="sortDirection = sortDirection === 'asc' ? 'desc' : 'asc'">
|
||||||
|
<ArrowUp v-if="sortDirection === 'asc'" class="h-3 w-3" />
|
||||||
|
<ArrowDown v-else class="h-3 w-3" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="flex h-7 shrink-0 items-center rounded border bg-muted/20 p-0.5">
|
||||||
|
<button type="button" class="flex h-6 w-6 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:text-foreground" :class="{ 'bg-background text-foreground shadow-sm': isListView }" :title="t('objects.viewList')" @click="setViewMode('list')">
|
||||||
|
<List class="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
<button type="button" class="flex h-6 w-6 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:text-foreground" :class="{ 'bg-background text-foreground shadow-sm': !isListView }" :title="t('objects.viewGrid')" @click="setViewMode('grid')">
|
||||||
|
<LayoutGrid class="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="icon" class="h-7 w-7" :title="t('contextMenu.refreshTab')" :disabled="loading" @click="refresh">
|
||||||
|
<RefreshCw class="h-3.5 w-3.5" :class="{ 'animate-spin': loading }" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="loading && rows.length === 0" class="flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground"><Loader2 class="h-4 w-4 animate-spin" />{{ t("objects.loading") }}</div>
|
||||||
|
<div v-else-if="error" class="flex flex-1 items-center justify-center px-6 text-center text-sm text-destructive">{{ t("databaseBrowser.loadFailed", { message: error }) }}</div>
|
||||||
|
<div v-else-if="visibleRows.length === 0" class="flex flex-1 items-center justify-center text-sm text-muted-foreground">{{ t("databaseBrowser.empty") }}</div>
|
||||||
|
<div v-else class="flex min-h-0 min-w-0 flex-1">
|
||||||
|
<div v-if="isListView" class="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-auto overflow-y-hidden">
|
||||||
|
<div class="grid h-7 shrink-0 items-center gap-3 border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground" :style="{ gridTemplateColumns, minWidth: `${gridMinWidth}px` }">
|
||||||
|
<div v-for="key in columns" :key="key" class="relative flex min-w-0 items-center">
|
||||||
|
<button class="flex min-w-0 items-center gap-1 truncate pr-4 text-left" type="button" @click="toggleSort(key)">
|
||||||
|
<span class="truncate">{{ columnLabel(key) }}</span
|
||||||
|
><component :is="sortIconFor(key)" v-if="sortIconFor(key)" class="h-3 w-3 shrink-0" />
|
||||||
|
</button>
|
||||||
|
<div
|
||||||
|
class="absolute -right-2 top-0 bottom-0 z-10 flex w-3 cursor-col-resize items-center justify-center text-muted-foreground/70 hover:bg-primary/30 hover:text-primary"
|
||||||
|
@mousedown="onColumnResizeStart(key, $event)"
|
||||||
|
@dblclick="resetColumnWidth(key, key === 'name' || key === 'comment' ? 260 : key === 'defaultCollation' ? 170 : key === 'defaultCharset' ? 130 : key === 'sizeBytes' ? 100 : 150, $event)"
|
||||||
|
>
|
||||||
|
<GripVertical class="h-3 w-3" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="min-h-0 flex-1 overflow-auto">
|
||||||
|
<div
|
||||||
|
v-for="row in visibleRows"
|
||||||
|
:key="row.name"
|
||||||
|
tabindex="0"
|
||||||
|
class="grid h-[34px] cursor-pointer items-center gap-3 border-b px-3 outline-none hover:bg-accent/50 focus-visible:bg-accent/50"
|
||||||
|
:style="{ gridTemplateColumns, minWidth: `${gridMinWidth}px` }"
|
||||||
|
@dblclick="openDatabase(row.name)"
|
||||||
|
@keydown.enter.prevent="openDatabase(row.name)"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
v-for="key in columns"
|
||||||
|
:key="key"
|
||||||
|
class="min-w-0 truncate text-xs text-muted-foreground"
|
||||||
|
:class="{ 'flex items-center gap-2 text-[13px] font-medium text-foreground': key === 'name', 'tabular-nums': key === 'sizeBytes' || key === 'createdAt' || key === 'updatedAt' }"
|
||||||
|
:title="displayValue(row, key)"
|
||||||
|
>
|
||||||
|
<Database v-if="key === 'name'" class="h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400" />
|
||||||
|
{{ displayValue(row, key) || "-" }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-else class="grid min-h-0 flex-1 grid-cols-[repeat(auto-fill,minmax(160px,1fr))] content-start gap-3 overflow-auto p-3">
|
||||||
|
<div
|
||||||
|
v-for="row in visibleRows"
|
||||||
|
:key="row.name"
|
||||||
|
tabindex="0"
|
||||||
|
class="flex min-h-28 cursor-pointer flex-col items-center gap-1 rounded-lg border bg-card p-3 text-center outline-none transition-all hover:border-primary/40 hover:shadow-sm focus-visible:border-primary"
|
||||||
|
@dblclick="openDatabase(row.name)"
|
||||||
|
@keydown.enter.prevent="openDatabase(row.name)"
|
||||||
|
>
|
||||||
|
<div class="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-emerald-500/10 shadow-sm"><Database class="h-6 w-6 text-emerald-600 dark:text-emerald-400" /></div>
|
||||||
|
<span class="w-full truncate text-sm font-medium text-foreground" :title="row.name">{{ row.name }}</span>
|
||||||
|
<div class="flex min-h-[15px] items-center gap-1 text-[10px] leading-[15px] text-muted-foreground">
|
||||||
|
<span v-if="row.sizeBytes != null">{{ formatObjectBrowserBytes(row.sizeBytes) }}</span
|
||||||
|
><span v-if="row.createdAt && row.sizeBytes != null">·</span><span v-if="row.createdAt">{{ formatObjectBrowserTimestamp(row.createdAt) }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="hasComment" class="w-full truncate text-[10px] leading-[15px] text-muted-foreground/60" :title="row.comment || ''">{{ row.comment || "\u00A0" }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
const source = readFileSync(new URL("../DatabaseBrowser.vue", import.meta.url), "utf8");
|
||||||
|
|
||||||
|
describe("DatabaseBrowser metadata fallback", () => {
|
||||||
|
it("falls back to basic database names when extended metadata fails", () => {
|
||||||
|
expect(source).toMatch(/await api\.listDatabaseMetadata\(props\.connection\.id\)[\s\S]*?catch \(metadataError\)[\s\S]*?await api\.listDatabases\(props\.connection\.id\)/);
|
||||||
|
expect(source).toMatch(/catch \{\s*throw metadataError;\s*\}/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -83,6 +83,7 @@ import {
|
|||||||
editableDatabasePropertyGroups,
|
editableDatabasePropertyGroups,
|
||||||
supportsDatabaseCreation,
|
supportsDatabaseCreation,
|
||||||
supportsDatabaseSearch,
|
supportsDatabaseSearch,
|
||||||
|
supportsConnectionDatabaseBrowser,
|
||||||
supportsConnectionQueryActions,
|
supportsConnectionQueryActions,
|
||||||
supportsFieldLineage,
|
supportsFieldLineage,
|
||||||
supportsObjectBrowserTreeNode,
|
supportsObjectBrowserTreeNode,
|
||||||
@@ -1135,8 +1136,10 @@ function requestDeleteSelectedNode(): boolean {
|
|||||||
|
|
||||||
function onDoubleClick(event: MouseEvent) {
|
function onDoubleClick(event: MouseEvent) {
|
||||||
if (dataTabOpenModeFromTreeClick(activeNode.value.type, event, settingsStore.editorSettings.shortcuts.openDataInNewTab) === "new-tab") return;
|
if (dataTabOpenModeFromTreeClick(activeNode.value.type, event, settingsStore.editorSettings.shortcuts.openDataInNewTab) === "new-tab") return;
|
||||||
const action = treeNodeRowDoubleClickAction(activeNode.value.type, canOpenObjectBrowser.value, settingsStore.editorSettings.sidebarActivation, canExpand.value, currentDatabaseType());
|
const action = treeNodeRowDoubleClickAction(activeNode.value.type, canOpenObjectBrowser.value, settingsStore.editorSettings.sidebarActivation, canExpand.value, currentDatabaseType(), canOpenConnectionDatabaseBrowser.value);
|
||||||
if (action === "open-object-browser") {
|
if (action === "open-database-browser") {
|
||||||
|
void openDatabaseBrowser();
|
||||||
|
} else if (action === "open-object-browser") {
|
||||||
void openObjectBrowser();
|
void openObjectBrowser();
|
||||||
} else if (action === "open-object-browser-and-expand") {
|
} else if (action === "open-object-browser-and-expand") {
|
||||||
void openObjectBrowser();
|
void openObjectBrowser();
|
||||||
@@ -1243,6 +1246,19 @@ async function openObjectBrowser() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function openDatabaseBrowser() {
|
||||||
|
const node = activeNode.value;
|
||||||
|
if (node.type !== "connection" || !node.connectionId) return;
|
||||||
|
try {
|
||||||
|
await connectionStore.ensureConnected(node.connectionId);
|
||||||
|
connectionStore.activeConnectionId = node.connectionId;
|
||||||
|
queryStore.openDatabaseBrowser(node.connectionId);
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
|
||||||
|
openDriverStoreForInstallError(e?.message || String(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function openUserAdmin() {
|
async function openUserAdmin() {
|
||||||
const node = activeNode.value;
|
const node = activeNode.value;
|
||||||
if (!node.connectionId) return;
|
if (!node.connectionId) return;
|
||||||
@@ -3491,6 +3507,10 @@ const canOpenObjectBrowser = computed(() => {
|
|||||||
return supportsObjectBrowserTreeNode(rawDatabaseType(), activeNode.value.type);
|
return supportsObjectBrowserTreeNode(rawDatabaseType(), activeNode.value.type);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const canOpenConnectionDatabaseBrowser = computed(() => {
|
||||||
|
return activeNode.value.type === "connection" && supportsConnectionDatabaseBrowser(rawDatabaseType());
|
||||||
|
});
|
||||||
|
|
||||||
const canOpenTableImport = computed(() => {
|
const canOpenTableImport = computed(() => {
|
||||||
const node = activeNode.value;
|
const node = activeNode.value;
|
||||||
const supportedNode = node.type === "table" || ((node.type === "database" || node.type === "schema" || node.type === "group-tables") && canCreateTable.value);
|
const supportedNode = node.type === "table" || ((node.type === "database" || node.type === "schema" || node.type === "group-tables") && canCreateTable.value);
|
||||||
@@ -4106,6 +4126,9 @@ function buildConnectionSidebarMenu(context: SidebarMenuFactoryContext): boolean
|
|||||||
if (supportsQueryActions) {
|
if (supportsQueryActions) {
|
||||||
items.push({ label: t("contextMenu.newQuery"), action: newQuery, icon: TerminalSquare });
|
items.push({ label: t("contextMenu.newQuery"), action: newQuery, icon: TerminalSquare });
|
||||||
}
|
}
|
||||||
|
if (canOpenConnectionDatabaseBrowser.value) {
|
||||||
|
items.push({ label: t("contextMenu.openDatabaseBrowser"), action: openDatabaseBrowser, icon: TableProperties });
|
||||||
|
}
|
||||||
if (currentDatabaseType() === "redis") {
|
if (currentDatabaseType() === "redis") {
|
||||||
items.push({ label: t("contextMenu.instanceInfo"), action: openRedisInstanceInfo, icon: Info });
|
items.push({ label: t("contextMenu.instanceInfo"), action: openRedisInstanceInfo, icon: Info });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1298,6 +1298,7 @@ export default {
|
|||||||
mongo: "Mongo",
|
mongo: "Mongo",
|
||||||
gridfs: "GridFS",
|
gridfs: "GridFS",
|
||||||
vector: "Vector",
|
vector: "Vector",
|
||||||
|
databases: "Databases",
|
||||||
objects: "Objects",
|
objects: "Objects",
|
||||||
users: "Users & Privileges",
|
users: "Users & Privileges",
|
||||||
executionSummary: "Summary",
|
executionSummary: "Summary",
|
||||||
@@ -1342,6 +1343,13 @@ export default {
|
|||||||
fixedTabs: "Fixed tabs",
|
fixedTabs: "Fixed tabs",
|
||||||
openDataTabs: "Open tables",
|
openDataTabs: "Open tables",
|
||||||
},
|
},
|
||||||
|
databaseBrowser: {
|
||||||
|
search: "Search databases...",
|
||||||
|
empty: "No databases found",
|
||||||
|
loadFailed: "Could not load databases: {message}",
|
||||||
|
defaultCharset: "Charset",
|
||||||
|
defaultCollation: "Collation",
|
||||||
|
},
|
||||||
gridfsBrowser: {
|
gridfsBrowser: {
|
||||||
bucketCount: "buckets",
|
bucketCount: "buckets",
|
||||||
fileCount: "files",
|
fileCount: "files",
|
||||||
@@ -2543,6 +2551,7 @@ export default {
|
|||||||
sqlHistory: "Query History",
|
sqlHistory: "Query History",
|
||||||
noSqlHistory: "No related SQL",
|
noSqlHistory: "No related SQL",
|
||||||
openObjectBrowser: "Browse Objects",
|
openObjectBrowser: "Browse Objects",
|
||||||
|
openDatabaseBrowser: "Browse Databases",
|
||||||
viewData: "View Data",
|
viewData: "View Data",
|
||||||
openInNewDataTab: "View in New Tab",
|
openInNewDataTab: "View in New Tab",
|
||||||
editStructure: "Edit Structure",
|
editStructure: "Edit Structure",
|
||||||
|
|||||||
@@ -1275,6 +1275,7 @@ export default withEnglishFallback({
|
|||||||
zookeeper: "ZooKeeper",
|
zookeeper: "ZooKeeper",
|
||||||
consul: "Consul",
|
consul: "Consul",
|
||||||
vector: "Vector",
|
vector: "Vector",
|
||||||
|
databases: "Bases de datos",
|
||||||
users: "Usuarios y Privilegios",
|
users: "Usuarios y Privilegios",
|
||||||
executionSummary: "Resumen",
|
executionSummary: "Resumen",
|
||||||
messages: "Mensajes",
|
messages: "Mensajes",
|
||||||
@@ -2482,6 +2483,7 @@ export default withEnglishFallback({
|
|||||||
sqlHistory: "Historial de consultas",
|
sqlHistory: "Historial de consultas",
|
||||||
noSqlHistory: "Sin SQL relacionado",
|
noSqlHistory: "Sin SQL relacionado",
|
||||||
openObjectBrowser: "Explorar objetos",
|
openObjectBrowser: "Explorar objetos",
|
||||||
|
openDatabaseBrowser: "Explorar bases de datos",
|
||||||
viewData: "Ver datos",
|
viewData: "Ver datos",
|
||||||
openInNewDataTab: "Ver en nueva pestaña",
|
openInNewDataTab: "Ver en nueva pestaña",
|
||||||
editStructure: "Editar estructura",
|
editStructure: "Editar estructura",
|
||||||
@@ -6285,6 +6287,13 @@ export default withEnglishFallback({
|
|||||||
registerInstance: "Registrar instancia",
|
registerInstance: "Registrar instancia",
|
||||||
deregister: "Dar de baja",
|
deregister: "Dar de baja",
|
||||||
},
|
},
|
||||||
|
databaseBrowser: {
|
||||||
|
search: "Buscar bases de datos...",
|
||||||
|
empty: "No se encontraron bases de datos",
|
||||||
|
loadFailed: "No se pudieron cargar las bases de datos: {message}",
|
||||||
|
defaultCharset: "Juego de caracteres",
|
||||||
|
defaultCollation: "Cotejamiento",
|
||||||
|
},
|
||||||
gridfsBrowser: {
|
gridfsBrowser: {
|
||||||
bucketCount: "Cantidad de buckets",
|
bucketCount: "Cantidad de buckets",
|
||||||
fileCount: "Archivos",
|
fileCount: "Archivos",
|
||||||
|
|||||||
@@ -1274,6 +1274,7 @@ export default withEnglishFallback({
|
|||||||
consul: "Consul",
|
consul: "Consul",
|
||||||
mongo: "Mongo",
|
mongo: "Mongo",
|
||||||
vector: "Vector",
|
vector: "Vector",
|
||||||
|
databases: "Database",
|
||||||
objects: "Oggetti",
|
objects: "Oggetti",
|
||||||
users: "Utenti e Privilegi",
|
users: "Utenti e Privilegi",
|
||||||
executionSummary: "Riepilogo",
|
executionSummary: "Riepilogo",
|
||||||
@@ -2480,6 +2481,7 @@ export default withEnglishFallback({
|
|||||||
sqlHistory: "Cronologia Query",
|
sqlHistory: "Cronologia Query",
|
||||||
noSqlHistory: "Nessun SQL correlato",
|
noSqlHistory: "Nessun SQL correlato",
|
||||||
openObjectBrowser: "Esplora Oggetti",
|
openObjectBrowser: "Esplora Oggetti",
|
||||||
|
openDatabaseBrowser: "Esplora database",
|
||||||
viewData: "Visualizza Dati",
|
viewData: "Visualizza Dati",
|
||||||
openInNewDataTab: "Visualizza in nuova scheda",
|
openInNewDataTab: "Visualizza in nuova scheda",
|
||||||
editStructure: "Modifica Struttura",
|
editStructure: "Modifica Struttura",
|
||||||
@@ -6285,6 +6287,13 @@ export default withEnglishFallback({
|
|||||||
registerInstance: "Registra istanza",
|
registerInstance: "Registra istanza",
|
||||||
deregister: "Rimuovi",
|
deregister: "Rimuovi",
|
||||||
},
|
},
|
||||||
|
databaseBrowser: {
|
||||||
|
search: "Cerca database...",
|
||||||
|
empty: "Nessun database trovato",
|
||||||
|
loadFailed: "Impossibile caricare i database: {message}",
|
||||||
|
defaultCharset: "Set di caratteri",
|
||||||
|
defaultCollation: "Regole di confronto",
|
||||||
|
},
|
||||||
gridfsBrowser: {
|
gridfsBrowser: {
|
||||||
bucketCount: "Bucket",
|
bucketCount: "Bucket",
|
||||||
fileCount: "File",
|
fileCount: "File",
|
||||||
|
|||||||
@@ -1293,6 +1293,7 @@ export default withEnglishFallback({
|
|||||||
etcd: "etcd",
|
etcd: "etcd",
|
||||||
mongo: "Mongo",
|
mongo: "Mongo",
|
||||||
objects: "オブジェクト",
|
objects: "オブジェクト",
|
||||||
|
databases: "データベース",
|
||||||
users: "ユーザーと権限",
|
users: "ユーザーと権限",
|
||||||
executionSummary: "サマリー",
|
executionSummary: "サマリー",
|
||||||
messages: "メッセージ",
|
messages: "メッセージ",
|
||||||
@@ -2505,6 +2506,7 @@ export default withEnglishFallback({
|
|||||||
sqlHistory: "クエリ履歴",
|
sqlHistory: "クエリ履歴",
|
||||||
noSqlHistory: "関連するSQLはありません",
|
noSqlHistory: "関連するSQLはありません",
|
||||||
openObjectBrowser: "オブジェクトを参照",
|
openObjectBrowser: "オブジェクトを参照",
|
||||||
|
openDatabaseBrowser: "データベースを参照",
|
||||||
viewData: "データを表示",
|
viewData: "データを表示",
|
||||||
openInNewDataTab: "新しいタブで表示",
|
openInNewDataTab: "新しいタブで表示",
|
||||||
editStructure: "構造を編集",
|
editStructure: "構造を編集",
|
||||||
@@ -6340,6 +6342,13 @@ export default withEnglishFallback({
|
|||||||
registerInstance: "インスタンスを登録",
|
registerInstance: "インスタンスを登録",
|
||||||
deregister: "解除",
|
deregister: "解除",
|
||||||
},
|
},
|
||||||
|
databaseBrowser: {
|
||||||
|
search: "データベースを検索...",
|
||||||
|
empty: "データベースが見つかりません",
|
||||||
|
loadFailed: "データベースを読み込めませんでした: {message}",
|
||||||
|
defaultCharset: "文字セット",
|
||||||
|
defaultCollation: "照合順序",
|
||||||
|
},
|
||||||
gridfsBrowser: {
|
gridfsBrowser: {
|
||||||
bucketCount: "バケット",
|
bucketCount: "バケット",
|
||||||
fileCount: "ファイル",
|
fileCount: "ファイル",
|
||||||
|
|||||||
@@ -1187,6 +1187,7 @@ export default withEnglishFallback({
|
|||||||
mongo: "Mongo",
|
mongo: "Mongo",
|
||||||
gridfs: "GridFS",
|
gridfs: "GridFS",
|
||||||
vector: "Vector",
|
vector: "Vector",
|
||||||
|
databases: "데이터베이스",
|
||||||
objects: "객체",
|
objects: "객체",
|
||||||
users: "사용자 및 권한",
|
users: "사용자 및 권한",
|
||||||
executionSummary: "요약",
|
executionSummary: "요약",
|
||||||
@@ -1231,6 +1232,13 @@ export default withEnglishFallback({
|
|||||||
fixedTabs: "고정 탭",
|
fixedTabs: "고정 탭",
|
||||||
openDataTabs: "열린 테이블",
|
openDataTabs: "열린 테이블",
|
||||||
},
|
},
|
||||||
|
databaseBrowser: {
|
||||||
|
search: "데이터베이스 검색...",
|
||||||
|
empty: "데이터베이스를 찾을 수 없습니다",
|
||||||
|
loadFailed: "데이터베이스를 불러올 수 없습니다: {message}",
|
||||||
|
defaultCharset: "문자 집합",
|
||||||
|
defaultCollation: "데이터 정렬",
|
||||||
|
},
|
||||||
gridfsBrowser: {
|
gridfsBrowser: {
|
||||||
bucketCount: "버킷",
|
bucketCount: "버킷",
|
||||||
fileCount: "파일",
|
fileCount: "파일",
|
||||||
@@ -2400,6 +2408,7 @@ export default withEnglishFallback({
|
|||||||
sqlHistory: "쿼리 기록",
|
sqlHistory: "쿼리 기록",
|
||||||
noSqlHistory: "관련 SQL이 없습니다",
|
noSqlHistory: "관련 SQL이 없습니다",
|
||||||
openObjectBrowser: "객체 탐색",
|
openObjectBrowser: "객체 탐색",
|
||||||
|
openDatabaseBrowser: "데이터베이스 탐색",
|
||||||
viewData: "데이터 보기",
|
viewData: "데이터 보기",
|
||||||
openInNewDataTab: "새 탭에서 보기",
|
openInNewDataTab: "새 탭에서 보기",
|
||||||
editStructure: "구조 편집",
|
editStructure: "구조 편집",
|
||||||
|
|||||||
@@ -1275,6 +1275,7 @@ export default withEnglishFallback({
|
|||||||
consul: "Consul",
|
consul: "Consul",
|
||||||
mongo: "Mongo",
|
mongo: "Mongo",
|
||||||
vector: "Vector",
|
vector: "Vector",
|
||||||
|
databases: "Bancos de dados",
|
||||||
objects: "Objetos",
|
objects: "Objetos",
|
||||||
users: "Usuários e Privilégios",
|
users: "Usuários e Privilégios",
|
||||||
executionSummary: "Resumo",
|
executionSummary: "Resumo",
|
||||||
@@ -2482,6 +2483,7 @@ export default withEnglishFallback({
|
|||||||
sqlHistory: "Histórico de Consultas",
|
sqlHistory: "Histórico de Consultas",
|
||||||
noSqlHistory: "Nenhum SQL relacionado",
|
noSqlHistory: "Nenhum SQL relacionado",
|
||||||
openObjectBrowser: "Explorar Objetos",
|
openObjectBrowser: "Explorar Objetos",
|
||||||
|
openDatabaseBrowser: "Explorar bancos de dados",
|
||||||
viewData: "Ver Dados",
|
viewData: "Ver Dados",
|
||||||
openInNewDataTab: "Ver em nova aba",
|
openInNewDataTab: "Ver em nova aba",
|
||||||
editStructure: "Editar Estrutura",
|
editStructure: "Editar Estrutura",
|
||||||
@@ -6287,6 +6289,13 @@ export default withEnglishFallback({
|
|||||||
registerInstance: "Registrar instância",
|
registerInstance: "Registrar instância",
|
||||||
deregister: "Remover registro",
|
deregister: "Remover registro",
|
||||||
},
|
},
|
||||||
|
databaseBrowser: {
|
||||||
|
search: "Pesquisar bancos de dados...",
|
||||||
|
empty: "Nenhum banco de dados encontrado",
|
||||||
|
loadFailed: "Não foi possível carregar os bancos de dados: {message}",
|
||||||
|
defaultCharset: "Conjunto de caracteres",
|
||||||
|
defaultCollation: "Agrupamento",
|
||||||
|
},
|
||||||
gridfsBrowser: {
|
gridfsBrowser: {
|
||||||
bucketCount: "Buckets",
|
bucketCount: "Buckets",
|
||||||
fileCount: "Arquivos",
|
fileCount: "Arquivos",
|
||||||
|
|||||||
@@ -1223,6 +1223,7 @@ export default withEnglishFallback({
|
|||||||
mongo: "Mongo",
|
mongo: "Mongo",
|
||||||
gridfs: "GridFS",
|
gridfs: "GridFS",
|
||||||
vector: "向量",
|
vector: "向量",
|
||||||
|
databases: "数据库",
|
||||||
objects: "对象",
|
objects: "对象",
|
||||||
users: "用户与权限",
|
users: "用户与权限",
|
||||||
executionSummary: "摘要",
|
executionSummary: "摘要",
|
||||||
@@ -1267,6 +1268,13 @@ export default withEnglishFallback({
|
|||||||
fixedTabs: "固定标签页",
|
fixedTabs: "固定标签页",
|
||||||
openDataTabs: "已打开的数据表",
|
openDataTabs: "已打开的数据表",
|
||||||
},
|
},
|
||||||
|
databaseBrowser: {
|
||||||
|
search: "搜索数据库...",
|
||||||
|
empty: "没有找到数据库",
|
||||||
|
loadFailed: "加载数据库失败:{message}",
|
||||||
|
defaultCharset: "默认字符集",
|
||||||
|
defaultCollation: "默认排序规则",
|
||||||
|
},
|
||||||
gridfsBrowser: {
|
gridfsBrowser: {
|
||||||
bucketCount: "\u5b58\u50a8\u6876",
|
bucketCount: "\u5b58\u50a8\u6876",
|
||||||
fileCount: "\u6587\u4ef6",
|
fileCount: "\u6587\u4ef6",
|
||||||
@@ -2468,6 +2476,7 @@ export default withEnglishFallback({
|
|||||||
sqlHistory: "历史查询",
|
sqlHistory: "历史查询",
|
||||||
noSqlHistory: "暂无关联 SQL",
|
noSqlHistory: "暂无关联 SQL",
|
||||||
openObjectBrowser: "浏览对象",
|
openObjectBrowser: "浏览对象",
|
||||||
|
openDatabaseBrowser: "查看资源对象",
|
||||||
viewData: "查看数据",
|
viewData: "查看数据",
|
||||||
openInNewDataTab: "新标签页查看",
|
openInNewDataTab: "新标签页查看",
|
||||||
editStructure: "编辑表结构",
|
editStructure: "编辑表结构",
|
||||||
|
|||||||
@@ -1274,6 +1274,7 @@ export default withEnglishFallback({
|
|||||||
consul: "Consul",
|
consul: "Consul",
|
||||||
mongo: "Mongo",
|
mongo: "Mongo",
|
||||||
vector: "向量",
|
vector: "向量",
|
||||||
|
databases: "資料庫",
|
||||||
objects: "物件",
|
objects: "物件",
|
||||||
users: "使用者與權限",
|
users: "使用者與權限",
|
||||||
executionSummary: "摘要",
|
executionSummary: "摘要",
|
||||||
@@ -2481,6 +2482,7 @@ export default withEnglishFallback({
|
|||||||
sqlHistory: "歷史查詢",
|
sqlHistory: "歷史查詢",
|
||||||
noSqlHistory: "暫無關聯 SQL",
|
noSqlHistory: "暫無關聯 SQL",
|
||||||
openObjectBrowser: "瀏覽物件",
|
openObjectBrowser: "瀏覽物件",
|
||||||
|
openDatabaseBrowser: "檢視資源物件",
|
||||||
viewData: "檢視資料",
|
viewData: "檢視資料",
|
||||||
openInNewDataTab: "新分頁檢視",
|
openInNewDataTab: "新分頁檢視",
|
||||||
editStructure: "編輯資料表結構",
|
editStructure: "編輯資料表結構",
|
||||||
@@ -6280,6 +6282,13 @@ export default withEnglishFallback({
|
|||||||
summarySize: "大小",
|
summarySize: "大小",
|
||||||
rootReadonly: "根 znode 不能被修改,請填寫子節點路徑",
|
rootReadonly: "根 znode 不能被修改,請填寫子節點路徑",
|
||||||
},
|
},
|
||||||
|
databaseBrowser: {
|
||||||
|
search: "搜尋資料庫...",
|
||||||
|
empty: "找不到資料庫",
|
||||||
|
loadFailed: "載入資料庫失敗:{message}",
|
||||||
|
defaultCharset: "預設字元集",
|
||||||
|
defaultCollation: "預設定序規則",
|
||||||
|
},
|
||||||
gridfsBrowser: {
|
gridfsBrowser: {
|
||||||
bucketCount: "儲存桶",
|
bucketCount: "儲存桶",
|
||||||
fileCount: "檔案",
|
fileCount: "檔案",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { buildGetDatabaseCommentSql } from "@/lib/database/dbAdminSql";
|
|||||||
import {
|
import {
|
||||||
isSchemaAware,
|
isSchemaAware,
|
||||||
supportsConnectionScopedQueryExecution,
|
supportsConnectionScopedQueryExecution,
|
||||||
|
supportsConnectionDatabaseBrowser,
|
||||||
supportsDatabaseNameCompletion,
|
supportsDatabaseNameCompletion,
|
||||||
supportsDatabaseSchemaQualifier,
|
supportsDatabaseSchemaQualifier,
|
||||||
supportsQueryTargetDatabaseListing,
|
supportsQueryTargetDatabaseListing,
|
||||||
@@ -20,6 +21,13 @@ describe("schema awareness", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("connection database browser", () => {
|
||||||
|
it("follows object browser support without enabling unsupported connection types", () => {
|
||||||
|
expect(supportsConnectionDatabaseBrowser("postgres")).toBe(true);
|
||||||
|
expect(supportsConnectionDatabaseBrowser("redis")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("connection-scoped query targets", () => {
|
describe("connection-scoped query targets", () => {
|
||||||
it("keeps connection-only target types separate from unregistered namespace targets", () => {
|
it("keeps connection-only target types separate from unregistered namespace targets", () => {
|
||||||
expect(usesConnectionOnlyQueryTarget("etcd")).toBe(true);
|
expect(usesConnectionOnlyQueryTarget("etcd")).toBe(true);
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { activeTabSidebarTarget, matchesTarget } from "@/lib/sidebar/sidebarActiveTabTarget";
|
||||||
|
import type { QueryTab, TreeNode } from "@/types/database";
|
||||||
|
|
||||||
|
describe("sidebar active-tab targets", () => {
|
||||||
|
it("selects the connection node for a database-browser tab", () => {
|
||||||
|
const target = activeTabSidebarTarget({ mode: "databases", connectionId: "pg-1" } as QueryTab);
|
||||||
|
|
||||||
|
expect(target).toEqual({ type: "connection", connectionId: "pg-1" });
|
||||||
|
expect(matchesTarget({ id: "connection:pg-1", label: "Postgres", type: "connection", connectionId: "pg-1" } as TreeNode, target!)).toBe(true);
|
||||||
|
expect(matchesTarget({ id: "connection:pg-2", label: "Other", type: "connection", connectionId: "pg-2" } as TreeNode, target!)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -44,6 +44,11 @@ describe("treeNodeClick", () => {
|
|||||||
expect(treeNodeRowAction("consul-overview", false, "double")).toBe("toggle");
|
expect(treeNodeRowAction("consul-overview", false, "double")).toBe("toggle");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("opens the connection database browser only when the capability is enabled", () => {
|
||||||
|
expect(treeNodeRowDoubleClickAction("connection", false, "single", true, "postgres", true)).toBe("open-database-browser");
|
||||||
|
expect(treeNodeRowDoubleClickAction("connection", false, "double", true, "postgres", false)).toBe("toggle");
|
||||||
|
});
|
||||||
|
|
||||||
it("expands package containers while preserving source behavior for leaf packages", () => {
|
it("expands package containers while preserving source behavior for leaf packages", () => {
|
||||||
expect(treeNodeRowAction("package", true)).toBe("toggle");
|
expect(treeNodeRowAction("package", true)).toBe("toggle");
|
||||||
expect(treeNodeRowAction("package", false)).toBe("open-source");
|
expect(treeNodeRowAction("package", false)).toBe("open-source");
|
||||||
|
|||||||
@@ -137,6 +137,7 @@ export const syncSavedSqlDirectory = forward("syncSavedSqlDirectory");
|
|||||||
|
|
||||||
// Schema
|
// Schema
|
||||||
export const listDatabases = forward("listDatabases");
|
export const listDatabases = forward("listDatabases");
|
||||||
|
export const listDatabaseMetadata = forward("listDatabaseMetadata");
|
||||||
export const listDatabaseStorage = forward("listDatabaseStorage");
|
export const listDatabaseStorage = forward("listDatabaseStorage");
|
||||||
export const getSqlServerCompletionContext = forward("getSqlServerCompletionContext");
|
export const getSqlServerCompletionContext = forward("getSqlServerCompletionContext");
|
||||||
export const listDorisCatalogs = forward("listDorisCatalogs");
|
export const listDorisCatalogs = forward("listDorisCatalogs");
|
||||||
|
|||||||
@@ -648,6 +648,10 @@ export async function listDatabases(connectionId: string): Promise<DatabaseInfo[
|
|||||||
return get(`/api/schema/databases?${qs({ connection_id: connectionId })}`);
|
return get(`/api/schema/databases?${qs({ connection_id: connectionId })}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function listDatabaseMetadata(connectionId: string): Promise<DatabaseInfo[]> {
|
||||||
|
return get(`/api/schema/database-metadata?${qs({ connection_id: connectionId })}`);
|
||||||
|
}
|
||||||
|
|
||||||
export async function listDatabaseStorage(connectionId: string, databases: string[]): Promise<DatabaseStorageInfo[]> {
|
export async function listDatabaseStorage(connectionId: string, databases: string[]): Promise<DatabaseStorageInfo[]> {
|
||||||
return post("/api/schema/database-storage", {
|
return post("/api/schema/database-storage", {
|
||||||
connection_id: connectionId,
|
connection_id: connectionId,
|
||||||
|
|||||||
@@ -928,6 +928,10 @@ export async function listDatabases(connectionId: string): Promise<DatabaseInfo[
|
|||||||
return invoke("list_databases", { connectionId });
|
return invoke("list_databases", { connectionId });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function listDatabaseMetadata(connectionId: string): Promise<DatabaseInfo[]> {
|
||||||
|
return invoke("list_database_metadata", { connectionId });
|
||||||
|
}
|
||||||
|
|
||||||
export async function listDatabaseStorage(connectionId: string, databases: string[]): Promise<DatabaseStorageInfo[]> {
|
export async function listDatabaseStorage(connectionId: string, databases: string[]): Promise<DatabaseStorageInfo[]> {
|
||||||
return invoke("list_database_storage", { connectionId, databases });
|
return invoke("list_database_storage", { connectionId, databases });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -167,6 +167,10 @@ export function supportsObjectBrowser(dbType?: DatabaseType): boolean {
|
|||||||
return supportsDatabaseFeature(dbType, "objectBrowser");
|
return supportsDatabaseFeature(dbType, "objectBrowser");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function supportsConnectionDatabaseBrowser(dbType?: DatabaseType): boolean {
|
||||||
|
return supportsObjectBrowser(dbType);
|
||||||
|
}
|
||||||
|
|
||||||
export function supportsObjectBrowserTreeNode(dbType: DatabaseType | undefined, nodeType: TreeNodeType): boolean {
|
export function supportsObjectBrowserTreeNode(dbType: DatabaseType | undefined, nodeType: TreeNodeType): boolean {
|
||||||
if (!supportsObjectBrowser(dbType)) return false;
|
if (!supportsObjectBrowser(dbType)) return false;
|
||||||
if (nodeType === "database" && usesDatabaseObjectTreeMode(dbType)) return true;
|
if (nodeType === "database" && usesDatabaseObjectTreeMode(dbType)) return true;
|
||||||
|
|||||||
@@ -2,6 +2,10 @@ import { SIDEBAR_TREE_ROW_HEIGHT, type FlatTreeNode } from "@/composables/useFla
|
|||||||
import type { QueryTab, TreeNode } from "@/types/database";
|
import type { QueryTab, TreeNode } from "@/types/database";
|
||||||
|
|
||||||
export type ActiveTabSidebarTarget =
|
export type ActiveTabSidebarTarget =
|
||||||
|
| {
|
||||||
|
type: "connection";
|
||||||
|
connectionId: string;
|
||||||
|
}
|
||||||
| {
|
| {
|
||||||
type: "table";
|
type: "table";
|
||||||
connectionId: string;
|
connectionId: string;
|
||||||
@@ -80,6 +84,10 @@ export type ActiveTabSidebarTarget =
|
|||||||
export function activeTabSidebarTarget(tab: QueryTab | undefined | null): ActiveTabSidebarTarget | null {
|
export function activeTabSidebarTarget(tab: QueryTab | undefined | null): ActiveTabSidebarTarget | null {
|
||||||
if (!tab) return null;
|
if (!tab) return null;
|
||||||
|
|
||||||
|
if (tab.mode === "databases") {
|
||||||
|
return { type: "connection", connectionId: tab.connectionId };
|
||||||
|
}
|
||||||
|
|
||||||
if (tab.mode === "data") {
|
if (tab.mode === "data") {
|
||||||
const tableName = tab.tableMeta?.tableName || tab.title;
|
const tableName = tab.tableMeta?.tableName || tab.title;
|
||||||
if (!tableName) return null;
|
if (!tableName) return null;
|
||||||
@@ -199,6 +207,10 @@ function schemaMatches(node: TreeNode, schema: string | undefined): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function matchesTarget(node: TreeNode, target: ActiveTabSidebarTarget): boolean {
|
export function matchesTarget(node: TreeNode, target: ActiveTabSidebarTarget): boolean {
|
||||||
|
if (target.type === "connection") {
|
||||||
|
return node.type === "connection" && node.connectionId === target.connectionId;
|
||||||
|
}
|
||||||
|
|
||||||
if (target.type === "mongo-collection") {
|
if (target.type === "mongo-collection") {
|
||||||
if (node.type === "elasticsearch-index") {
|
if (node.type === "elasticsearch-index") {
|
||||||
return node.connectionId === target.connectionId && node.label === target.collectionName;
|
return node.connectionId === target.connectionId && node.label === target.collectionName;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { customTypeCapabilities, supportsTypeObjectSource } from "@/lib/database
|
|||||||
import { matchesShortcut, type ShortcutLikeEvent } from "@/lib/editor/keyboardShortcuts";
|
import { matchesShortcut, type ShortcutLikeEvent } from "@/lib/editor/keyboardShortcuts";
|
||||||
|
|
||||||
export type TreeNodeRowAction = "open-data" | "open-source" | "open-extension-details" | "toggle" | "none";
|
export type TreeNodeRowAction = "open-data" | "open-source" | "open-extension-details" | "toggle" | "none";
|
||||||
export type TreeNodeRowDoubleClickAction = "open-data" | "activate-data" | "open-object-browser" | "open-object-browser-and-expand" | "open-source" | "open-extension-details" | "open-saved-sql" | "toggle" | "none";
|
export type TreeNodeRowDoubleClickAction = "open-data" | "activate-data" | "open-database-browser" | "open-object-browser" | "open-object-browser-and-expand" | "open-source" | "open-extension-details" | "open-saved-sql" | "toggle" | "none";
|
||||||
export type SidebarSelectionCopyAction = "copy-name" | "none";
|
export type SidebarSelectionCopyAction = "copy-name" | "none";
|
||||||
export type SidebarActivation = "single" | "double";
|
export type SidebarActivation = "single" | "double";
|
||||||
|
|
||||||
@@ -120,10 +120,11 @@ export function shouldRunTreeNodeRowAction(action: TreeNodeRowAction, clickDetai
|
|||||||
return action !== "none" && clickDetail <= 1;
|
return action !== "none" && clickDetail <= 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function treeNodeRowDoubleClickAction(type: TreeNodeType, canOpenObjectBrowser: boolean, activation: SidebarActivation = "single", canExpand = false, dbType?: DatabaseType): TreeNodeRowDoubleClickAction {
|
export function treeNodeRowDoubleClickAction(type: TreeNodeType, canOpenObjectBrowser: boolean, activation: SidebarActivation = "single", canExpand = false, dbType?: DatabaseType, canOpenDatabaseBrowser = false): TreeNodeRowDoubleClickAction {
|
||||||
// Single-click activation already handles the first click in a dblclick
|
// Single-click activation already handles the first click in a dblclick
|
||||||
// sequence. Only double-click activation needs a second-stage table action.
|
// sequence. Only double-click activation needs a second-stage table action.
|
||||||
if (type === "table") return activation === "double" ? "activate-data" : "none";
|
if (type === "table") return activation === "double" ? "activate-data" : "none";
|
||||||
|
if (type === "connection" && canOpenDatabaseBrowser) return "open-database-browser";
|
||||||
if (activation === "double") {
|
if (activation === "double") {
|
||||||
if (type === "extension") return "open-extension-details";
|
if (type === "extension") return "open-extension-details";
|
||||||
if (dataNodeTypes.has(type)) return "open-data";
|
if (dataNodeTypes.has(type)) return "open-data";
|
||||||
|
|||||||
@@ -130,6 +130,10 @@ export function tabDisplayTitle(tab: QueryTab, t: Translate): string {
|
|||||||
if (tab.mode === "mqtt") {
|
if (tab.mode === "mqtt") {
|
||||||
return `${connectionDisplayName(tab.connectionId)} - ${t("connection.mqttConsoleTitle")}`;
|
return `${connectionDisplayName(tab.connectionId)} - ${t("connection.mqttConsoleTitle")}`;
|
||||||
}
|
}
|
||||||
|
if (tab.mode === "databases") {
|
||||||
|
if (compact) return t("tabs.databases");
|
||||||
|
return `${t("tabs.databases")}@${connectionDisplayName(tab.connectionId)}`;
|
||||||
|
}
|
||||||
if (tab.mode === "objects") {
|
if (tab.mode === "objects") {
|
||||||
const schema = tab.objectBrowser?.schema;
|
const schema = tab.objectBrowser?.schema;
|
||||||
if (compact) return schema || tab.title;
|
if (compact) return schema || tab.title;
|
||||||
@@ -436,6 +440,7 @@ export function tabModeLabel(tab: QueryTab, t: Translate): string {
|
|||||||
if (tab.mode === "consul") return t("tabs.consul");
|
if (tab.mode === "consul") return t("tabs.consul");
|
||||||
if (tab.mode === "consul-overview") return t("consul.ui.overview");
|
if (tab.mode === "consul-overview") return t("consul.ui.overview");
|
||||||
if (tab.mode === "nacos") return "Nacos";
|
if (tab.mode === "nacos") return "Nacos";
|
||||||
|
if (tab.mode === "databases") return t("tabs.databases");
|
||||||
if (tab.mode === "objects") return t("tabs.objects");
|
if (tab.mode === "objects") return t("tabs.objects");
|
||||||
if (tab.mode === "users") return t("tabs.users");
|
if (tab.mode === "users") return t("tabs.users");
|
||||||
return tab.mode;
|
return tab.mode;
|
||||||
|
|||||||
@@ -40,6 +40,20 @@ describe("queryStore database open state", () => {
|
|||||||
expect(store.isDatabaseOpen("pg-1", "analytics")).toBe(false);
|
expect(store.isDatabaseOpen("pg-1", "analytics")).toBe(false);
|
||||||
}, 10_000);
|
}, 10_000);
|
||||||
|
|
||||||
|
it("reuses one database browser tab per connection", async () => {
|
||||||
|
const { useQueryStore } = await import("@/stores/queryStore");
|
||||||
|
const store = useQueryStore();
|
||||||
|
|
||||||
|
const firstId = store.openDatabaseBrowser("pg-1");
|
||||||
|
const secondId = store.openDatabaseBrowser("pg-1");
|
||||||
|
const otherConnectionId = store.openDatabaseBrowser("pg-2");
|
||||||
|
|
||||||
|
expect(secondId).toBe(firstId);
|
||||||
|
expect(otherConnectionId).not.toBe(firstId);
|
||||||
|
expect(store.tabs.filter((tab) => tab.mode === "databases")).toHaveLength(2);
|
||||||
|
expect(store.tabs.find((tab) => tab.id === firstId)).toMatchObject({ connectionId: "pg-1", database: "", mode: "databases" });
|
||||||
|
});
|
||||||
|
|
||||||
it("keeps object browser viewport per tab and clears it on schema change", async () => {
|
it("keeps object browser viewport per tab and clears it on schema change", async () => {
|
||||||
const { useQueryStore } = await import("@/stores/queryStore");
|
const { useQueryStore } = await import("@/stores/queryStore");
|
||||||
const store = useQueryStore();
|
const store = useQueryStore();
|
||||||
|
|||||||
@@ -1702,6 +1702,29 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function openDatabaseBrowser(connectionId: string) {
|
||||||
|
const existing = tabs.value.find((tab) => tab.mode === "databases" && tab.connectionId === connectionId);
|
||||||
|
if (existing) {
|
||||||
|
switchTab(existing.id);
|
||||||
|
return existing.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = uuid();
|
||||||
|
tabs.value.push({
|
||||||
|
id,
|
||||||
|
title: "Databases",
|
||||||
|
connectionId,
|
||||||
|
database: "",
|
||||||
|
sql: "",
|
||||||
|
isExecuting: false,
|
||||||
|
isCancelling: false,
|
||||||
|
isExplaining: false,
|
||||||
|
mode: "databases",
|
||||||
|
});
|
||||||
|
activeTabId.value = id;
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
function switchTab(tabId: string) {
|
function switchTab(tabId: string) {
|
||||||
activeTabId.value = tabId;
|
activeTabId.value = tabId;
|
||||||
settingsStore.settingsPageActive = false;
|
settingsStore.settingsPageActive = false;
|
||||||
@@ -5736,6 +5759,7 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
commitTransaction,
|
commitTransaction,
|
||||||
rollbackTransaction,
|
rollbackTransaction,
|
||||||
renameTab,
|
renameTab,
|
||||||
|
openDatabaseBrowser,
|
||||||
openObjectBrowser,
|
openObjectBrowser,
|
||||||
openMongoGridFs,
|
openMongoGridFs,
|
||||||
openMongoBucket,
|
openMongoBucket,
|
||||||
|
|||||||
@@ -381,6 +381,12 @@ export interface JdbcPluginStatus {
|
|||||||
|
|
||||||
export interface DatabaseInfo {
|
export interface DatabaseInfo {
|
||||||
name: string;
|
name: string;
|
||||||
|
size_bytes?: number | null;
|
||||||
|
created_at?: string | null;
|
||||||
|
updated_at?: string | null;
|
||||||
|
comment?: string | null;
|
||||||
|
default_charset?: string | null;
|
||||||
|
default_collation?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DatabaseStorageInfo {
|
export interface DatabaseStorageInfo {
|
||||||
@@ -1140,6 +1146,7 @@ export interface QueryTab {
|
|||||||
| "mqtt"
|
| "mqtt"
|
||||||
| "nacos"
|
| "nacos"
|
||||||
| "nacos-dashboard"
|
| "nacos-dashboard"
|
||||||
|
| "databases"
|
||||||
| "objects"
|
| "objects"
|
||||||
| "structure"
|
| "structure"
|
||||||
| "users"
|
| "users"
|
||||||
|
|||||||
@@ -607,7 +607,11 @@ pub async fn test_connection(client: &ChClient, timeout: Duration) -> Result<(),
|
|||||||
|
|
||||||
pub async fn list_databases(client: &ChClient) -> Result<Vec<DatabaseInfo>, String> {
|
pub async fn list_databases(client: &ChClient) -> Result<Vec<DatabaseInfo>, String> {
|
||||||
let result = ch_query(client, "SELECT name FROM system.databases ORDER BY name", None).await?;
|
let result = ch_query(client, "SELECT name FROM system.databases ORDER BY name", None).await?;
|
||||||
Ok(result.data.iter().map(|row| DatabaseInfo { name: row[0].as_str().unwrap_or("").to_string() }).collect())
|
Ok(result
|
||||||
|
.data
|
||||||
|
.iter()
|
||||||
|
.map(|row| DatabaseInfo { name: row[0].as_str().unwrap_or("").to_string(), ..Default::default() })
|
||||||
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_tables(client: &ChClient, database: &str) -> Result<Vec<TableInfo>, String> {
|
pub async fn list_tables(client: &ChClient, database: &str) -> Result<Vec<TableInfo>, String> {
|
||||||
|
|||||||
@@ -111,7 +111,7 @@ pub async fn connect(config: &ConnectionConfig, timeout: Duration) -> Result<Clo
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_databases(_client: &CloudflareD1Client) -> Result<Vec<DatabaseInfo>, String> {
|
pub async fn list_databases(_client: &CloudflareD1Client) -> Result<Vec<DatabaseInfo>, String> {
|
||||||
Ok(vec![DatabaseInfo { name: "main".to_string() }])
|
Ok(vec![DatabaseInfo { name: "main".to_string(), ..Default::default() }])
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_tables(client: &CloudflareD1Client, _schema: &str) -> Result<Vec<TableInfo>, String> {
|
pub async fn list_tables(client: &CloudflareD1Client, _schema: &str) -> Result<Vec<TableInfo>, String> {
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ fn database_infos(names: Vec<String>) -> Vec<DatabaseInfo> {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|name| name.trim().to_string())
|
.map(|name| name.trim().to_string())
|
||||||
.filter(|name| !name.is_empty())
|
.filter(|name| !name.is_empty())
|
||||||
.map(|name| DatabaseInfo { name })
|
.map(|name| DatabaseInfo { name, ..Default::default() })
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -226,7 +226,7 @@ pub async fn list_namespaces(client: &HBaseClient) -> Result<Vec<DatabaseInfo>,
|
|||||||
let body: RestNamespaces = parse_success_json(response, "list namespaces").await?;
|
let body: RestNamespaces = parse_success_json(response, "list namespaces").await?;
|
||||||
let mut namespaces = body.namespaces;
|
let mut namespaces = body.namespaces;
|
||||||
namespaces.sort_by_key(|name| name.to_ascii_lowercase());
|
namespaces.sort_by_key(|name| name.to_ascii_lowercase());
|
||||||
Ok(namespaces.into_iter().map(|name| DatabaseInfo { name }).collect())
|
Ok(namespaces.into_iter().map(|name| DatabaseInfo { name, ..Default::default() }).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_tables(client: &HBaseClient, namespace: &str) -> Result<Vec<TableInfo>, String> {
|
pub async fn list_tables(client: &HBaseClient, namespace: &str) -> Result<Vec<TableInfo>, String> {
|
||||||
|
|||||||
@@ -347,7 +347,7 @@ pub async fn list_databases(client: &InfluxdbClient) -> Result<Vec<DatabaseInfo>
|
|||||||
return Ok(influx_v2_buckets(client, Duration::from_secs(30))
|
return Ok(influx_v2_buckets(client, Duration::from_secs(30))
|
||||||
.await?
|
.await?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|bucket| DatabaseInfo { name: bucket.name })
|
.map(|bucket| DatabaseInfo { name: bucket.name, ..Default::default() })
|
||||||
.collect());
|
.collect());
|
||||||
}
|
}
|
||||||
let result = influx_query(client, "SHOW DATABASES", None).await?;
|
let result = influx_query(client, "SHOW DATABASES", None).await?;
|
||||||
@@ -356,7 +356,7 @@ pub async fn list_databases(client: &InfluxdbClient) -> Result<Vec<DatabaseInfo>
|
|||||||
.iter()
|
.iter()
|
||||||
.flat_map(|r| &r.series)
|
.flat_map(|r| &r.series)
|
||||||
.flat_map(|s| &s.values)
|
.flat_map(|s| &s.values)
|
||||||
.map(|row| DatabaseInfo { name: row[0].as_str().unwrap_or("").to_string() })
|
.map(|row| DatabaseInfo { name: row[0].as_str().unwrap_or("").to_string(), ..Default::default() })
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1989,6 +1989,14 @@ pub async fn connect_bare_with_pool_limit_and_setup_database(
|
|||||||
const SHOW_DATABASES_SQL: &str = "SHOW DATABASES";
|
const SHOW_DATABASES_SQL: &str = "SHOW DATABASES";
|
||||||
const INFORMATION_SCHEMA_DATABASES_SQL: &str =
|
const INFORMATION_SCHEMA_DATABASES_SQL: &str =
|
||||||
"SELECT SCHEMA_NAME FROM information_schema.SCHEMATA ORDER BY SCHEMA_NAME";
|
"SELECT SCHEMA_NAME FROM information_schema.SCHEMATA ORDER BY SCHEMA_NAME";
|
||||||
|
const DATABASE_METADATA_SQL: &str = "SELECT s.SCHEMA_NAME, \
|
||||||
|
s.DEFAULT_CHARACTER_SET_NAME, \
|
||||||
|
s.DEFAULT_COLLATION_NAME, \
|
||||||
|
SUM(COALESCE(t.DATA_LENGTH, 0) + COALESCE(t.INDEX_LENGTH, 0)) AS SIZE_BYTES \
|
||||||
|
FROM information_schema.SCHEMATA s \
|
||||||
|
LEFT JOIN information_schema.TABLES t ON t.TABLE_SCHEMA = s.SCHEMA_NAME \
|
||||||
|
GROUP BY s.SCHEMA_NAME, s.DEFAULT_CHARACTER_SET_NAME, s.DEFAULT_COLLATION_NAME \
|
||||||
|
ORDER BY s.SCHEMA_NAME";
|
||||||
const DATABASE_LIST_QUERY_PLAN: [(&str, bool); 2] =
|
const DATABASE_LIST_QUERY_PLAN: [(&str, bool); 2] =
|
||||||
[(SHOW_DATABASES_SQL, true), (INFORMATION_SCHEMA_DATABASES_SQL, false)];
|
[(SHOW_DATABASES_SQL, true), (INFORMATION_SCHEMA_DATABASES_SQL, false)];
|
||||||
|
|
||||||
@@ -2003,6 +2011,40 @@ pub async fn list_databases(pool: &MySqlPool) -> Result<Vec<DatabaseInfo>, Strin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn list_database_metadata(pool: &MySqlPool) -> Result<Vec<DatabaseInfo>, String> {
|
||||||
|
let mut conn = get_conn_with_timeout(pool, super::connection_timeout()).await?;
|
||||||
|
let result = match conn.query_iter(DATABASE_METADATA_SQL).await {
|
||||||
|
Ok(result) => result,
|
||||||
|
Err(error) => {
|
||||||
|
log::debug!("Falling back to database names after metadata query failed: {error}");
|
||||||
|
drop(conn);
|
||||||
|
return list_databases(pool).await;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let rows: Vec<mysql_async::Row> = match result.collect_and_drop().await {
|
||||||
|
Ok(rows) => rows,
|
||||||
|
Err(error) => {
|
||||||
|
log::debug!("Falling back to database names after metadata query failed: {error}");
|
||||||
|
drop(conn);
|
||||||
|
return list_databases(pool).await;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(rows
|
||||||
|
.iter()
|
||||||
|
.filter_map(|row| {
|
||||||
|
let name = get_str(row, 0).trim().to_string();
|
||||||
|
(!name.is_empty()).then_some(DatabaseInfo {
|
||||||
|
name,
|
||||||
|
size_bytes: get_opt_i64(row, "SIZE_BYTES"),
|
||||||
|
default_charset: get_opt_str(row, "DEFAULT_CHARACTER_SET_NAME")
|
||||||
|
.filter(|value| !value.trim().is_empty()),
|
||||||
|
default_collation: get_opt_str(row, "DEFAULT_COLLATION_NAME").filter(|value| !value.trim().is_empty()),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
async fn list_databases_with_query(
|
async fn list_databases_with_query(
|
||||||
pool: &MySqlPool,
|
pool: &MySqlPool,
|
||||||
sql: &str,
|
sql: &str,
|
||||||
@@ -2028,12 +2070,12 @@ pub(super) fn database_infos_from_names(
|
|||||||
.filter_map(|name| {
|
.filter_map(|name| {
|
||||||
saw_row = true;
|
saw_row = true;
|
||||||
let name = name.trim().to_string();
|
let name = name.trim().to_string();
|
||||||
(!name.is_empty()).then_some(DatabaseInfo { name })
|
(!name.is_empty()).then_some(DatabaseInfo { name, ..Default::default() })
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
databases.sort_by(|a, b| a.name.cmp(&b.name));
|
databases.sort_by(|a, b| a.name.cmp(&b.name));
|
||||||
if databases.is_empty() && saw_row && include_catalogless_when_blank {
|
if databases.is_empty() && saw_row && include_catalogless_when_blank {
|
||||||
return vec![DatabaseInfo { name: String::new() }];
|
return vec![DatabaseInfo { name: String::new(), ..Default::default() }];
|
||||||
}
|
}
|
||||||
databases
|
databases
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ pub async fn list_databases(pool: &mysql_async::Pool) -> Result<Vec<DatabaseInfo
|
|||||||
let result = conn.query_iter(list_user_schemas_sql()).await.map_err(|e| e.to_string())?;
|
let result = conn.query_iter(list_user_schemas_sql()).await.map_err(|e| e.to_string())?;
|
||||||
let rows: Vec<mysql_async::Row> = result.collect_and_drop().await.map_err(|e| e.to_string())?;
|
let rows: Vec<mysql_async::Row> = result.collect_and_drop().await.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
Ok(rows.iter().map(|row| DatabaseInfo { name: get_str(row, 0) }).collect())
|
Ok(rows.iter().map(|row| DatabaseInfo { name: get_str(row, 0), ..Default::default() }).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_schemas(pool: &mysql_async::Pool) -> Result<Vec<String>, String> {
|
pub async fn list_schemas(pool: &mysql_async::Pool) -> Result<Vec<String>, String> {
|
||||||
|
|||||||
@@ -2316,11 +2316,31 @@ fn validate_postgres_ssl_paths(url: &str) -> Result<(), String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn list_databases_sql() -> &'static str {
|
fn list_databases_sql() -> &'static str {
|
||||||
"SELECT datname FROM pg_database \
|
"SELECT datname \
|
||||||
|
FROM pg_database \
|
||||||
WHERE datallowconn = true \
|
WHERE datallowconn = true \
|
||||||
ORDER BY datname"
|
ORDER BY datname"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn database_metadata_sql() -> &'static str {
|
||||||
|
"SELECT d.datname, \
|
||||||
|
CASE \
|
||||||
|
WHEN has_database_privilege(d.datname, 'CONNECT') \
|
||||||
|
OR COALESCE(( \
|
||||||
|
SELECT pg_has_role(current_user, r.oid, 'MEMBER') \
|
||||||
|
FROM pg_roles r \
|
||||||
|
WHERE r.rolname = 'pg_read_all_stats' \
|
||||||
|
), false) \
|
||||||
|
THEN pg_database_size(d.oid) \
|
||||||
|
ELSE NULL \
|
||||||
|
END AS size_bytes, \
|
||||||
|
obj_description(d.oid, 'pg_database') AS comment, \
|
||||||
|
pg_encoding_to_char(d.encoding) AS default_charset \
|
||||||
|
FROM pg_database d \
|
||||||
|
WHERE datallowconn = true \
|
||||||
|
ORDER BY d.datname"
|
||||||
|
}
|
||||||
|
|
||||||
fn database_storage_sql() -> &'static str {
|
fn database_storage_sql() -> &'static str {
|
||||||
"SELECT d.datname, \
|
"SELECT d.datname, \
|
||||||
CASE \
|
CASE \
|
||||||
@@ -2343,7 +2363,26 @@ pub async fn list_databases(pool: &Pool) -> Result<Vec<DatabaseInfo>, String> {
|
|||||||
let client = checkout_postgres_client(pool, None, super::connection_timeout()).await?;
|
let client = checkout_postgres_client(pool, None, super::connection_timeout()).await?;
|
||||||
let rows = postgres_query_cached(&client, list_databases_sql(), &[]).await.map_err(|e| e.to_string())?;
|
let rows = postgres_query_cached(&client, list_databases_sql(), &[]).await.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
Ok(rows.iter().map(|row| DatabaseInfo { name: pg_row_try_string(row, 0) }).collect())
|
Ok(rows.iter().map(|row| DatabaseInfo { name: pg_row_try_string(row, 0), ..Default::default() }).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_database_metadata(pool: &Pool) -> Result<Vec<DatabaseInfo>, String> {
|
||||||
|
let client = checkout_postgres_client(pool, None, super::connection_timeout()).await?;
|
||||||
|
let rows = postgres_query_cached(&client, database_metadata_sql(), &[]).await.map_err(|e| e.to_string())?;
|
||||||
|
Ok(rows
|
||||||
|
.iter()
|
||||||
|
.map(|row| DatabaseInfo {
|
||||||
|
name: pg_row_try_string(row, 0),
|
||||||
|
size_bytes: row.try_get::<_, Option<i64>>(1).ok().flatten(),
|
||||||
|
comment: row.try_get::<_, Option<String>>(2).ok().flatten().filter(|value| !value.trim().is_empty()),
|
||||||
|
default_charset: row
|
||||||
|
.try_get::<_, Option<String>>(3)
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.filter(|value| !value.trim().is_empty()),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_database_storage(pool: &Pool, database_names: &[String]) -> Result<Vec<DatabaseStorageInfo>, String> {
|
pub async fn list_database_storage(pool: &Pool, database_names: &[String]) -> Result<Vec<DatabaseStorageInfo>, String> {
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ pub async fn test_connection(client: &RqliteClient, timeout: Duration) -> Result
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_databases(_client: &RqliteClient) -> Result<Vec<DatabaseInfo>, String> {
|
pub async fn list_databases(_client: &RqliteClient) -> Result<Vec<DatabaseInfo>, String> {
|
||||||
Ok(vec![DatabaseInfo { name: "main".to_string() }])
|
Ok(vec![DatabaseInfo { name: "main".to_string(), ..Default::default() }])
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_tables(client: &RqliteClient, _schema: &str) -> Result<Vec<TableInfo>, String> {
|
pub async fn list_tables(client: &RqliteClient, _schema: &str) -> Result<Vec<TableInfo>, String> {
|
||||||
|
|||||||
@@ -1284,7 +1284,7 @@ pub async fn list_databases(pool: &SqliteHandle) -> Result<Vec<DatabaseInfo>, St
|
|||||||
let mut stmt = conn.prepare("PRAGMA database_list").map_err(|e| e.to_string())?;
|
let mut stmt = conn.prepare("PRAGMA database_list").map_err(|e| e.to_string())?;
|
||||||
let rows = stmt.query_map([], |row| row.get::<_, String>("name")).map_err(|e| e.to_string())?;
|
let rows = stmt.query_map([], |row| row.get::<_, String>("name")).map_err(|e| e.to_string())?;
|
||||||
rows.filter_map(|row| match row {
|
rows.filter_map(|row| match row {
|
||||||
Ok(name) if !name.eq_ignore_ascii_case("temp") => Some(Ok(DatabaseInfo { name })),
|
Ok(name) if !name.eq_ignore_ascii_case("temp") => Some(Ok(DatabaseInfo { name, ..Default::default() })),
|
||||||
Ok(_) => None,
|
Ok(_) => None,
|
||||||
Err(error) => Some(Err(error)),
|
Err(error) => Some(Err(error)),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1722,7 +1722,47 @@ pub async fn list_databases(client: &mut SqlServerClient) -> Result<Vec<Database
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
let rows = stream.into_first_result().await.map_err(|e| e.to_string())?;
|
let rows = stream.into_first_result().await.map_err(|e| e.to_string())?;
|
||||||
Ok(rows.iter().map(|row| DatabaseInfo { name: row.get::<&str, _>(0).unwrap_or("").to_string() }).collect())
|
Ok(rows
|
||||||
|
.iter()
|
||||||
|
.map(|row| DatabaseInfo { name: row.get::<&str, _>(0).unwrap_or("").to_string(), ..Default::default() })
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_database_metadata(client: &mut SqlServerClient) -> Result<Vec<DatabaseInfo>, String> {
|
||||||
|
let rows = match list_database_metadata_rows(client).await {
|
||||||
|
Ok(rows) => rows,
|
||||||
|
Err(error) => {
|
||||||
|
log::debug!("Falling back to database names after metadata query failed: {error}");
|
||||||
|
return list_databases(client).await;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(rows
|
||||||
|
.iter()
|
||||||
|
.map(|row| DatabaseInfo {
|
||||||
|
name: row.get::<&str, _>(0).unwrap_or("").to_string(),
|
||||||
|
created_at: row.get::<chrono::NaiveDateTime, _>(1).map(|value| value.to_string()),
|
||||||
|
default_collation: row.get::<&str, _>(2).map(str::to_string).filter(|value| !value.trim().is_empty()),
|
||||||
|
size_bytes: row.get::<i64, _>(3),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn list_database_metadata_rows(client: &mut SqlServerClient) -> Result<Vec<Row>, String> {
|
||||||
|
let stream = client
|
||||||
|
.query(
|
||||||
|
"SELECT d.name, d.create_date, d.collation_name, \
|
||||||
|
SUM(COALESCE(CONVERT(bigint, f.size), 0)) * 8192 AS size_bytes \
|
||||||
|
FROM sys.databases d \
|
||||||
|
LEFT JOIN sys.master_files f ON f.database_id = d.database_id \
|
||||||
|
WHERE d.state = 0 \
|
||||||
|
GROUP BY d.name, d.create_date, d.collation_name \
|
||||||
|
ORDER BY d.name",
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let stream = stream.map_err(|error| error.to_string())?;
|
||||||
|
stream.into_first_result().await.map_err(|error| error.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_completion_context(client: &mut SqlServerClient) -> Result<SqlServerCompletionContext, String> {
|
pub async fn get_completion_context(client: &mut SqlServerClient) -> Result<SqlServerCompletionContext, String> {
|
||||||
@@ -1776,7 +1816,7 @@ pub async fn list_linked_server_catalogs(
|
|||||||
Ok(rows
|
Ok(rows
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|row| row.get::<&str, _>(0).map(str::trim).filter(|name| !name.is_empty()))
|
.filter_map(|row| row.get::<&str, _>(0).map(str::trim).filter(|name| !name.is_empty()))
|
||||||
.map(|name| DatabaseInfo { name: name.to_string() })
|
.map(|name| DatabaseInfo { name: name.to_string(), ..Default::default() })
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -140,7 +140,7 @@ pub async fn test_connection(client: &TursoClient, timeout: Duration) -> Result<
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_databases(_client: &TursoClient) -> Result<Vec<DatabaseInfo>, String> {
|
pub async fn list_databases(_client: &TursoClient) -> Result<Vec<DatabaseInfo>, String> {
|
||||||
Ok(vec![DatabaseInfo { name: "main".to_string() }])
|
Ok(vec![DatabaseInfo { name: "main".to_string(), ..Default::default() }])
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_tables(client: &TursoClient, _schema: &str) -> Result<Vec<TableInfo>, String> {
|
pub async fn list_tables(client: &TursoClient, _schema: &str) -> Result<Vec<TableInfo>, String> {
|
||||||
|
|||||||
@@ -183,7 +183,7 @@ pub async fn test_connection(client: &VictoriaMetricsClient, timeout: Duration)
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_databases(client: &VictoriaMetricsClient) -> Result<Vec<DatabaseInfo>, String> {
|
pub async fn list_databases(client: &VictoriaMetricsClient) -> Result<Vec<DatabaseInfo>, String> {
|
||||||
Ok(vec![DatabaseInfo { name: client.database_label.clone() }])
|
Ok(vec![DatabaseInfo { name: client.database_label.clone(), ..Default::default() }])
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_tables(client: &VictoriaMetricsClient) -> Result<Vec<TableInfo>, String> {
|
pub async fn list_tables(client: &VictoriaMetricsClient) -> Result<Vec<TableInfo>, String> {
|
||||||
|
|||||||
@@ -174,6 +174,16 @@ pub async fn list_databases_core(state: &AppState, connection_id: &str) -> Resul
|
|||||||
retry_metadata_connection(state, connection_id, None, || list_databases_once(state, connection_id)).await
|
retry_metadata_connection(state, connection_id, None, || list_databases_once(state, connection_id)).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Loads the more expensive database-level properties needed only by the
|
||||||
|
/// connection resource browser. General metadata paths keep using
|
||||||
|
/// `list_databases_core`, which only enumerates names.
|
||||||
|
pub async fn list_database_metadata_core(
|
||||||
|
state: &AppState,
|
||||||
|
connection_id: &str,
|
||||||
|
) -> Result<Vec<db::DatabaseInfo>, String> {
|
||||||
|
retry_metadata_connection(state, connection_id, None, || list_database_metadata_once(state, connection_id)).await
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn list_database_storage_core(
|
pub async fn list_database_storage_core(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
connection_id: &str,
|
connection_id: &str,
|
||||||
@@ -592,7 +602,7 @@ async fn list_databases_once(state: &AppState, connection_id: &str) -> Result<Ve
|
|||||||
if is_mongo {
|
if is_mongo {
|
||||||
drop(connections);
|
drop(connections);
|
||||||
let dbs = crate::mongo_ops::mongo_list_databases_core(state, connection_id).await?;
|
let dbs = crate::mongo_ops::mongo_list_databases_core(state, connection_id).await?;
|
||||||
return Ok(dbs.into_iter().map(|name| db::DatabaseInfo { name }).collect());
|
return Ok(dbs.into_iter().map(|name| db::DatabaseInfo { name, ..Default::default() }).collect());
|
||||||
}
|
}
|
||||||
drop(connections);
|
drop(connections);
|
||||||
let mut client = client.lock().await;
|
let mut client = client.lock().await;
|
||||||
@@ -632,6 +642,35 @@ async fn list_databases_once(state: &AppState, connection_id: &str) -> Result<Ve
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn list_database_metadata_once(state: &AppState, connection_id: &str) -> Result<Vec<db::DatabaseInfo>, String> {
|
||||||
|
let config = connection_config(state, connection_id).await;
|
||||||
|
if config.as_ref().is_some_and(|config| db::dolt::is_config(config) || is_doris_family_config(config)) {
|
||||||
|
return list_databases_once(state, connection_id).await;
|
||||||
|
}
|
||||||
|
let connections = state.connections.read().await;
|
||||||
|
if let Some(client) = extract_pool!(&connections, connection_id, SqlServer) {
|
||||||
|
drop(connections);
|
||||||
|
let mut client = client.lock().await;
|
||||||
|
return db::sqlserver::list_database_metadata(&mut client).await;
|
||||||
|
}
|
||||||
|
if let Some(PoolKind::Mysql(pool, mode)) = connections.get(connection_id) {
|
||||||
|
let pool = pool.clone();
|
||||||
|
let mode = *mode;
|
||||||
|
drop(connections);
|
||||||
|
return if mode == MysqlMode::OceanBaseOracle {
|
||||||
|
db::ob_oracle::list_databases(&pool).await
|
||||||
|
} else {
|
||||||
|
db::mysql::list_database_metadata(&pool).await
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if let Some(pool) = extract_pool!(&connections, connection_id, Postgres) {
|
||||||
|
drop(connections);
|
||||||
|
return db::postgres::list_database_metadata(&pool).await;
|
||||||
|
}
|
||||||
|
drop(connections);
|
||||||
|
list_databases_once(state, connection_id).await
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn list_schemas_core(state: &AppState, connection_id: &str, database: &str) -> Result<Vec<String>, String> {
|
pub async fn list_schemas_core(state: &AppState, connection_id: &str, database: &str) -> Result<Vec<String>, String> {
|
||||||
list_schemas_core_with_visible_filter(state, connection_id, database, false).await
|
list_schemas_core_with_visible_filter(state, connection_id, database, false).await
|
||||||
}
|
}
|
||||||
@@ -3347,7 +3386,7 @@ for line in sys.stdin:
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn test_database_info(name: &str) -> super::db::DatabaseInfo {
|
fn test_database_info(name: &str) -> super::db::DatabaseInfo {
|
||||||
super::db::DatabaseInfo { name: name.to_string() }
|
super::db::DatabaseInfo { name: name.to_string(), ..Default::default() }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1,8 +1,20 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
pub struct DatabaseInfo {
|
pub struct DatabaseInfo {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub size_bytes: Option<i64>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub created_at: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub updated_at: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub comment: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub default_charset: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub default_collation: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
|||||||
@@ -390,6 +390,7 @@ async fn main() {
|
|||||||
.route("/agents/progress/{operationId}", get(routes::agents::agent_progress))
|
.route("/agents/progress/{operationId}", get(routes::agents::agent_progress))
|
||||||
// Schema
|
// Schema
|
||||||
.route("/schema/databases", get(routes::schema::list_databases))
|
.route("/schema/databases", get(routes::schema::list_databases))
|
||||||
|
.route("/schema/database-metadata", get(routes::schema::list_database_metadata))
|
||||||
.route("/schema/database-storage", post(routes::schema::list_database_storage))
|
.route("/schema/database-storage", post(routes::schema::list_database_storage))
|
||||||
.route("/schema/sqlserver/completion-context", get(routes::schema::get_sqlserver_completion_context))
|
.route("/schema/sqlserver/completion-context", get(routes::schema::get_sqlserver_completion_context))
|
||||||
.route("/schema/doris/catalogs", get(routes::schema::list_doris_catalogs))
|
.route("/schema/doris/catalogs", get(routes::schema::list_doris_catalogs))
|
||||||
|
|||||||
@@ -42,6 +42,15 @@ pub async fn list_databases(
|
|||||||
Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))
|
Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn list_database_metadata(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Query(q): Query<SchemaQuery>,
|
||||||
|
) -> Result<Json<serde_json::Value>, AppError> {
|
||||||
|
let result =
|
||||||
|
dbx_core::schema::list_database_metadata_core(&state.app, &q.connection_id).await.map_err(AppError::from)?;
|
||||||
|
Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn list_database_storage(
|
pub async fn list_database_storage(
|
||||||
State(state): State<Arc<WebState>>,
|
State(state): State<Arc<WebState>>,
|
||||||
Json(request): Json<DatabaseStorageRequest>,
|
Json(request): Json<DatabaseStorageRequest>,
|
||||||
|
|||||||
@@ -19,6 +19,14 @@ pub async fn list_databases(
|
|||||||
dbx_core::schema::list_databases_core(&state, &connection_id).await
|
dbx_core::schema::list_databases_core(&state, &connection_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn list_database_metadata(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
connection_id: String,
|
||||||
|
) -> Result<Vec<db::DatabaseInfo>, String> {
|
||||||
|
dbx_core::schema::list_database_metadata_core(&state, &connection_id).await
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn list_database_storage(
|
pub async fn list_database_storage(
|
||||||
state: State<'_, Arc<AppState>>,
|
state: State<'_, Arc<AppState>>,
|
||||||
|
|||||||
@@ -1629,6 +1629,7 @@ pub fn run() {
|
|||||||
commands::plugins::install_jdbc_plugin_local,
|
commands::plugins::install_jdbc_plugin_local,
|
||||||
commands::plugins::uninstall_jdbc_plugin,
|
commands::plugins::uninstall_jdbc_plugin,
|
||||||
commands::schema::list_databases,
|
commands::schema::list_databases,
|
||||||
|
commands::schema::list_database_metadata,
|
||||||
commands::schema::list_database_storage,
|
commands::schema::list_database_storage,
|
||||||
commands::schema::get_sqlserver_completion_context,
|
commands::schema::get_sqlserver_completion_context,
|
||||||
commands::schema::list_doris_catalogs,
|
commands::schema::list_doris_catalogs,
|
||||||
|
|||||||
Reference in new issue
Block a user