feat(mongo): add GridFS manager for MongoDB
* feat(mongo): browse GridFS buckets and files Refs #2342 * feat(mongo): add GridFS manager for MongoDB * chore(i18n): autofill new translations --------- Co-authored-by: dbx-i18n-bot <github-actions[bot]@users.noreply.github.com> Co-authored-by: t8y2 <1156263951@qq.com>
This commit is contained in:
35 files changed
+1959
-39
No files matched your search
@@ -0,0 +1,271 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from "vue";
|
||||||
|
import { useI18n } from "vue-i18n";
|
||||||
|
import { Download, RefreshCcw, Trash2, Upload } from "@lucide/vue";
|
||||||
|
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useToast } from "@/composables/useToast";
|
||||||
|
import { downloadBinaryCellPayload, type BinaryCellDownloadPayload } from "@/lib/binaryCellDownload";
|
||||||
|
import { isTauriRuntime } from "@/lib/tauriRuntime";
|
||||||
|
import * as api from "@/lib/api";
|
||||||
|
import { useConnectionStore } from "@/stores/connectionStore";
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
connectionId: string;
|
||||||
|
database: string;
|
||||||
|
bucket: string;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const { toast } = useToast();
|
||||||
|
const connectionStore = useConnectionStore();
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const uploading = ref(false);
|
||||||
|
const deleting = ref(false);
|
||||||
|
const error = ref("");
|
||||||
|
const files = ref<Awaited<ReturnType<typeof api.documentListGridFsFiles>>>([]);
|
||||||
|
const selectedFileId = ref("");
|
||||||
|
const showDeleteConfirm = ref(false);
|
||||||
|
|
||||||
|
const totalBytes = computed(() => files.value.reduce((sum, file) => sum + (file.length || 0), 0));
|
||||||
|
const selectedFile = computed(() => files.value.find((file) => file.id === selectedFileId.value) || null);
|
||||||
|
const selectedMetadata = computed(() => (selectedFile.value?.metadata ? JSON.stringify(selectedFile.value.metadata, null, 2) : ""));
|
||||||
|
const isReadonly = computed(() => connectionStore.getConfig(props.connectionId)?.read_only ?? false);
|
||||||
|
|
||||||
|
function formatBytes(bytes: number): string {
|
||||||
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;
|
||||||
|
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;
|
||||||
|
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function displayName(file: (typeof files.value)[number]): string {
|
||||||
|
return file.filename || file.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadFiles() {
|
||||||
|
loading.value = true;
|
||||||
|
error.value = "";
|
||||||
|
try {
|
||||||
|
const nextFiles = await api.documentListGridFsFiles(props.connectionId, props.database, props.bucket);
|
||||||
|
files.value = nextFiles;
|
||||||
|
if (selectedFileId.value && !nextFiles.some((file) => file.id === selectedFileId.value)) {
|
||||||
|
selectedFileId.value = "";
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
error.value = e?.message || String(e);
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadFile(file: (typeof files.value)[number]) {
|
||||||
|
try {
|
||||||
|
const bytes = await api.documentDownloadGridFsFile(props.connectionId, props.database, props.bucket, file.id);
|
||||||
|
const payload: BinaryCellDownloadPayload = {
|
||||||
|
data: bytes,
|
||||||
|
mimeType: file.contentType || "application/octet-stream",
|
||||||
|
extension: file.filename?.includes(".") ? file.filename.split(".").pop() || "bin" : "bin",
|
||||||
|
};
|
||||||
|
const result = await downloadBinaryCellPayload(payload, displayName(file));
|
||||||
|
if (result.kind === "saved") {
|
||||||
|
toast(t("grid.exported"), 2500);
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e?.message || String(e), 5000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pickUploadFile(): Promise<{ name: string; data: Uint8Array; contentType?: string } | null> {
|
||||||
|
if (isTauriRuntime()) {
|
||||||
|
const [{ open }, fs] = await Promise.all([import("@tauri-apps/plugin-dialog"), import("@tauri-apps/plugin-fs")]);
|
||||||
|
const selected = await open({ multiple: false });
|
||||||
|
const path = Array.isArray(selected) ? selected[0] : selected;
|
||||||
|
if (!path || typeof path !== "string") return null;
|
||||||
|
const data = await fs.readFile(path);
|
||||||
|
const name = path.split(/[\\/]/).pop() || "file";
|
||||||
|
return { name, data };
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const input = document.createElement("input");
|
||||||
|
input.type = "file";
|
||||||
|
input.onchange = async () => {
|
||||||
|
try {
|
||||||
|
const file = input.files?.[0];
|
||||||
|
if (!file) {
|
||||||
|
resolve(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = new Uint8Array(await file.arrayBuffer());
|
||||||
|
resolve({ name: file.name, data, contentType: file.type || undefined });
|
||||||
|
} catch (error) {
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
input.click();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadFile() {
|
||||||
|
if (uploading.value) return;
|
||||||
|
try {
|
||||||
|
const selected = await pickUploadFile();
|
||||||
|
if (!selected) return;
|
||||||
|
uploading.value = true;
|
||||||
|
const fileId = await api.documentUploadGridFsFile(props.connectionId, props.database, props.bucket, selected.name, selected.data, selected.contentType);
|
||||||
|
await loadFiles();
|
||||||
|
selectedFileId.value = fileId;
|
||||||
|
toast(t("gridfsBrowser.fileUploaded", { fileName: selected.name }), 2500);
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e?.message || String(e), 5000);
|
||||||
|
} finally {
|
||||||
|
uploading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteSelectedFile() {
|
||||||
|
const file = selectedFile.value;
|
||||||
|
if (!file || deleting.value) return;
|
||||||
|
deleting.value = true;
|
||||||
|
try {
|
||||||
|
await api.documentDeleteGridFsFile(props.connectionId, props.database, props.bucket, file.id);
|
||||||
|
showDeleteConfirm.value = false;
|
||||||
|
selectedFileId.value = "";
|
||||||
|
await loadFiles();
|
||||||
|
toast(t("gridfsBrowser.fileDeleted", { fileName: displayName(file) }), 2500);
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e?.message || String(e), 5000);
|
||||||
|
} finally {
|
||||||
|
deleting.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
void loadFiles();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex h-full min-h-0 flex-col">
|
||||||
|
<div class="border-b border-border px-4 py-3">
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<div class="truncate text-sm font-semibold">{{ database }}.{{ bucket }}</div>
|
||||||
|
<div class="text-xs text-muted-foreground">{{ files.length }} {{ t("gridfsBrowser.fileCount") }} / {{ formatBytes(totalBytes) }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<Button size="sm" class="h-8 gap-1.5" :disabled="isReadonly || uploading" @click="uploadFile">
|
||||||
|
<Upload class="h-3.5 w-3.5" />
|
||||||
|
{{ t("gridfsBrowser.uploadFile") }}
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" class="h-8 gap-1.5" :disabled="!selectedFile" @click="selectedFile && downloadFile(selectedFile)">
|
||||||
|
<Download class="h-3.5 w-3.5" />
|
||||||
|
{{ t("gridfsBrowser.downloadFile") }}
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" size="sm" class="h-8 gap-1.5" :disabled="isReadonly || !selectedFile || deleting" @click="showDeleteConfirm = true">
|
||||||
|
<Trash2 class="h-3.5 w-3.5" />
|
||||||
|
{{ t("gridfsBrowser.deleteFile") }}
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" class="h-8 gap-1.5" :disabled="loading" @click="loadFiles">
|
||||||
|
<RefreshCcw class="h-3.5 w-3.5" :class="{ 'animate-spin': loading }" />
|
||||||
|
{{ t("grid.refresh") }}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="error" class="px-4 py-3 text-sm text-destructive">
|
||||||
|
{{ error }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="loading && files.length === 0" class="flex flex-1 items-center justify-center text-sm text-muted-foreground">
|
||||||
|
{{ t("executionSummary.executing") }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="files.length === 0" class="flex flex-1 items-center justify-center px-6 text-sm text-muted-foreground">
|
||||||
|
{{ t("gridfsBrowser.emptyFiles") }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else class="min-h-0 flex-1 flex-col xl:flex-row xl:divide-x xl:divide-border">
|
||||||
|
<div class="min-h-0 flex-1 overflow-auto">
|
||||||
|
<table class="min-w-full border-collapse text-sm">
|
||||||
|
<thead class="sticky top-0 z-10 bg-background">
|
||||||
|
<tr class="border-b border-border text-left text-xs text-muted-foreground">
|
||||||
|
<th class="px-4 py-2 font-medium">{{ t("gridfsBrowser.name") }}</th>
|
||||||
|
<th class="px-4 py-2 font-medium">ID</th>
|
||||||
|
<th class="px-4 py-2 font-medium">{{ t("gridfsBrowser.totalSize") }}</th>
|
||||||
|
<th class="px-4 py-2 font-medium">{{ t("gridfsBrowser.chunkSize") }}</th>
|
||||||
|
<th class="px-4 py-2 font-medium">{{ t("gridfsBrowser.uploadDate") }}</th>
|
||||||
|
<th class="px-4 py-2 font-medium">{{ t("gridfsBrowser.contentType") }}</th>
|
||||||
|
<th class="px-4 py-2 font-medium">MD5</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="file in files" :key="file.id" class="cursor-pointer border-b border-border/60 transition-colors hover:bg-muted/40" :class="{ 'bg-accent/45': selectedFileId === file.id }" @click="selectedFileId = file.id" @dblclick="downloadFile(file)">
|
||||||
|
<td class="px-4 py-2 align-top">
|
||||||
|
<div class="font-medium">{{ displayName(file) }}</div>
|
||||||
|
<div v-if="file.aliases?.length" class="mt-1 text-xs text-muted-foreground">{{ file.aliases.join(", ") }}</div>
|
||||||
|
</td>
|
||||||
|
<td class="px-4 py-2 align-top text-xs text-muted-foreground">{{ file.id }}</td>
|
||||||
|
<td class="px-4 py-2 align-top text-muted-foreground">{{ formatBytes(file.length) }}</td>
|
||||||
|
<td class="px-4 py-2 align-top text-muted-foreground">{{ formatBytes(file.chunkSize || 0) }}</td>
|
||||||
|
<td class="px-4 py-2 align-top text-muted-foreground">{{ file.uploadDate || "-" }}</td>
|
||||||
|
<td class="px-4 py-2 align-top text-muted-foreground">{{ file.contentType || "-" }}</td>
|
||||||
|
<td class="px-4 py-2 align-top text-xs text-muted-foreground">{{ file.md5 || "-" }}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside class="border-t border-border px-4 py-4 xl:w-80 xl:shrink-0 xl:border-t-0">
|
||||||
|
<template v-if="selectedFile">
|
||||||
|
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">{{ t("tabs.gridfs") }}</div>
|
||||||
|
<div class="mt-2 break-all text-lg font-semibold">{{ displayName(selectedFile) }}</div>
|
||||||
|
<div class="mt-1 break-all text-xs text-muted-foreground">{{ selectedFile.id }}</div>
|
||||||
|
|
||||||
|
<div class="mt-5 space-y-4 text-sm">
|
||||||
|
<div>
|
||||||
|
<div class="text-xs text-muted-foreground">{{ t("gridfsBrowser.totalSize") }}</div>
|
||||||
|
<div class="mt-1 font-medium">{{ formatBytes(selectedFile.length) }}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="text-xs text-muted-foreground">{{ t("gridfsBrowser.chunkSize") }}</div>
|
||||||
|
<div class="mt-1 font-medium">{{ formatBytes(selectedFile.chunkSize || 0) }}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="text-xs text-muted-foreground">{{ t("gridfsBrowser.uploadDate") }}</div>
|
||||||
|
<div class="mt-1 font-medium">{{ selectedFile.uploadDate || "-" }}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="text-xs text-muted-foreground">{{ t("gridfsBrowser.contentType") }}</div>
|
||||||
|
<div class="mt-1 break-all font-medium">{{ selectedFile.contentType || "-" }}</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="selectedFile.md5">
|
||||||
|
<div class="text-xs text-muted-foreground">MD5</div>
|
||||||
|
<div class="mt-1 break-all font-medium">{{ selectedFile.md5 }}</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="selectedMetadata">
|
||||||
|
<div class="text-xs text-muted-foreground">{{ t("gridfsBrowser.metadata") }}</div>
|
||||||
|
<pre class="mt-1 max-h-44 overflow-auto rounded bg-muted px-3 py-2 text-xs whitespace-pre-wrap">{{ selectedMetadata }}</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<div v-else class="text-sm text-muted-foreground">
|
||||||
|
{{ t("gridfsBrowser.selectFile") }}
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DangerConfirmDialog
|
||||||
|
v-model:open="showDeleteConfirm"
|
||||||
|
:loading="deleting"
|
||||||
|
:title="t('gridfsBrowser.deleteFileTitle')"
|
||||||
|
:message="t('gridfsBrowser.deleteFileMessage')"
|
||||||
|
:details="selectedFile ? displayName(selectedFile) : ''"
|
||||||
|
:confirm-label="t('gridfsBrowser.deleteFile')"
|
||||||
|
@confirm="deleteSelectedFile"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from "vue";
|
||||||
|
import { useI18n } from "vue-i18n";
|
||||||
|
import { FolderOpen, Plus, RefreshCcw, Trash2 } from "@lucide/vue";
|
||||||
|
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { useToast } from "@/composables/useToast";
|
||||||
|
import * as api from "@/lib/api";
|
||||||
|
import { useConnectionStore } from "@/stores/connectionStore";
|
||||||
|
import { useQueryStore } from "@/stores/queryStore";
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
connectionId: string;
|
||||||
|
database: string;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const { toast } = useToast();
|
||||||
|
const queryStore = useQueryStore();
|
||||||
|
const connectionStore = useConnectionStore();
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const creating = ref(false);
|
||||||
|
const deleting = ref(false);
|
||||||
|
const error = ref("");
|
||||||
|
const buckets = ref<Awaited<ReturnType<typeof api.documentListGridFsBuckets>>>([]);
|
||||||
|
const selectedBucketName = ref("");
|
||||||
|
const showCreateDialog = ref(false);
|
||||||
|
const showDeleteConfirm = ref(false);
|
||||||
|
const newBucketName = ref("");
|
||||||
|
|
||||||
|
const selectedBucket = computed(() => buckets.value.find((bucket) => bucket.name === selectedBucketName.value) || null);
|
||||||
|
const totalFiles = computed(() => buckets.value.reduce((sum, bucket) => sum + bucket.fileCount, 0));
|
||||||
|
const totalBytes = computed(() => buckets.value.reduce((sum, bucket) => sum + bucket.totalBytes, 0));
|
||||||
|
const isReadonly = computed(() => connectionStore.getConfig(props.connectionId)?.read_only ?? false);
|
||||||
|
|
||||||
|
function formatBytes(bytes: number): string {
|
||||||
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;
|
||||||
|
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;
|
||||||
|
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadBuckets() {
|
||||||
|
loading.value = true;
|
||||||
|
error.value = "";
|
||||||
|
try {
|
||||||
|
const nextBuckets = await api.documentListGridFsBuckets(props.connectionId, props.database);
|
||||||
|
buckets.value = nextBuckets;
|
||||||
|
if (selectedBucketName.value && !nextBuckets.some((bucket) => bucket.name === selectedBucketName.value)) {
|
||||||
|
selectedBucketName.value = "";
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
error.value = e?.message || String(e);
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openBucket(bucketName = selectedBucketName.value) {
|
||||||
|
if (!bucketName) return;
|
||||||
|
queryStore.openMongoBucket(props.connectionId, props.database, bucketName);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createBucket() {
|
||||||
|
const bucketName = newBucketName.value.trim();
|
||||||
|
if (!bucketName || creating.value) return;
|
||||||
|
creating.value = true;
|
||||||
|
try {
|
||||||
|
await api.documentCreateGridFsBucket(props.connectionId, props.database, bucketName);
|
||||||
|
showCreateDialog.value = false;
|
||||||
|
newBucketName.value = "";
|
||||||
|
selectedBucketName.value = bucketName;
|
||||||
|
await loadBuckets();
|
||||||
|
toast(t("gridfsBrowser.bucketCreated", { bucket: bucketName }), 2500);
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e?.message || String(e), 5000);
|
||||||
|
} finally {
|
||||||
|
creating.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteBucket() {
|
||||||
|
const bucketName = selectedBucketName.value;
|
||||||
|
if (!bucketName || deleting.value) return;
|
||||||
|
deleting.value = true;
|
||||||
|
try {
|
||||||
|
await api.documentDeleteGridFsBucket(props.connectionId, props.database, bucketName);
|
||||||
|
showDeleteConfirm.value = false;
|
||||||
|
selectedBucketName.value = "";
|
||||||
|
await loadBuckets();
|
||||||
|
toast(t("gridfsBrowser.bucketDeleted", { bucket: bucketName }), 2500);
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(e?.message || String(e), 5000);
|
||||||
|
} finally {
|
||||||
|
deleting.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
void loadBuckets();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex h-full min-h-0 flex-col">
|
||||||
|
<div class="border-b border-border px-4 py-3">
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<div class="truncate text-sm font-semibold">{{ database }} / {{ t("tabs.gridfs") }}</div>
|
||||||
|
<div class="text-xs text-muted-foreground">{{ buckets.length }} {{ t("gridfsBrowser.bucketCount") }} / {{ totalFiles }} {{ t("gridfsBrowser.fileCount") }} / {{ formatBytes(totalBytes) }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<Button size="sm" class="h-8 gap-1.5" :disabled="isReadonly" @click="showCreateDialog = true">
|
||||||
|
<Plus class="h-3.5 w-3.5" />
|
||||||
|
{{ t("gridfsBrowser.createBucket") }}
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" class="h-8 gap-1.5" :disabled="!selectedBucket" @click="openBucket()">
|
||||||
|
<FolderOpen class="h-3.5 w-3.5" />
|
||||||
|
{{ t("gridfsBrowser.openBucket") }}
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" size="sm" class="h-8 gap-1.5" :disabled="isReadonly || !selectedBucket || deleting" @click="showDeleteConfirm = true">
|
||||||
|
<Trash2 class="h-3.5 w-3.5" />
|
||||||
|
{{ t("gridfsBrowser.deleteBucket") }}
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" class="h-8 gap-1.5" :disabled="loading" @click="loadBuckets">
|
||||||
|
<RefreshCcw class="h-3.5 w-3.5" :class="{ 'animate-spin': loading }" />
|
||||||
|
{{ t("grid.refresh") }}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="error" class="px-4 py-3 text-sm text-destructive">
|
||||||
|
{{ error }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="loading && buckets.length === 0" class="flex flex-1 items-center justify-center text-sm text-muted-foreground">
|
||||||
|
{{ t("executionSummary.executing") }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="buckets.length === 0" class="flex flex-1 items-center justify-center px-6 text-sm text-muted-foreground">
|
||||||
|
{{ t("gridfsBrowser.emptyBuckets") }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else class="min-h-0 flex-1 flex-col xl:flex-row xl:divide-x xl:divide-border">
|
||||||
|
<div class="min-h-0 flex-1 overflow-auto">
|
||||||
|
<table class="min-w-full border-collapse text-sm">
|
||||||
|
<thead class="sticky top-0 z-10 bg-background">
|
||||||
|
<tr class="border-b border-border text-left text-xs text-muted-foreground">
|
||||||
|
<th class="px-4 py-2 font-medium">{{ t("gridfsBrowser.name") }}</th>
|
||||||
|
<th class="px-4 py-2 font-medium">{{ t("gridfsBrowser.fileCount") }}</th>
|
||||||
|
<th class="px-4 py-2 font-medium">{{ t("gridfsBrowser.totalSize") }}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="bucket in buckets" :key="bucket.name" class="cursor-pointer border-b border-border/60 transition-colors hover:bg-muted/40" :class="{ 'bg-accent/45': selectedBucketName === bucket.name }" @click="selectedBucketName = bucket.name" @dblclick="openBucket(bucket.name)">
|
||||||
|
<td class="px-4 py-2 font-medium">{{ bucket.name }}</td>
|
||||||
|
<td class="px-4 py-2 text-muted-foreground">{{ bucket.fileCount }}</td>
|
||||||
|
<td class="px-4 py-2 text-muted-foreground">{{ formatBytes(bucket.totalBytes) }}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside class="border-t border-border px-4 py-4 xl:w-72 xl:shrink-0 xl:border-t-0">
|
||||||
|
<template v-if="selectedBucket">
|
||||||
|
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">{{ t("tabs.gridfs") }}</div>
|
||||||
|
<div class="mt-2 break-all text-lg font-semibold">{{ selectedBucket.name }}</div>
|
||||||
|
|
||||||
|
<div class="mt-5 space-y-4 text-sm">
|
||||||
|
<div>
|
||||||
|
<div class="text-xs text-muted-foreground">{{ t("gridfsBrowser.fileCount") }}</div>
|
||||||
|
<div class="mt-1 font-medium">{{ selectedBucket.fileCount }}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="text-xs text-muted-foreground">{{ t("gridfsBrowser.totalSize") }}</div>
|
||||||
|
<div class="mt-1 font-medium">{{ formatBytes(selectedBucket.totalBytes) }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<div v-else class="text-sm text-muted-foreground">
|
||||||
|
{{ t("gridfsBrowser.selectBucket") }}
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Dialog v-model:open="showCreateDialog">
|
||||||
|
<DialogContent class="sm:max-w-[420px]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{{ t("gridfsBrowser.createTitle") }}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<div class="space-y-2 py-2">
|
||||||
|
<label class="text-sm font-medium">{{ t("gridfsBrowser.bucketName") }}</label>
|
||||||
|
<Input v-model="newBucketName" :placeholder="t('gridfsBrowser.bucketNamePlaceholder')" @keydown.enter="createBucket" />
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" :disabled="creating" @click="showCreateDialog = false">{{ t("common.cancel") }}</Button>
|
||||||
|
<Button :disabled="creating || !newBucketName.trim()" class="gap-1.5" @click="createBucket">
|
||||||
|
<RefreshCcw v-if="creating" class="h-3.5 w-3.5 animate-spin" />
|
||||||
|
{{ t("gridfsBrowser.createBucket") }}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<DangerConfirmDialog v-model:open="showDeleteConfirm" :loading="deleting" :title="t('gridfsBrowser.deleteTitle')" :message="t('gridfsBrowser.deleteMessage')" :details="selectedBucketName" :confirm-label="t('gridfsBrowser.deleteBucket')" @confirm="deleteBucket" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -39,6 +39,8 @@ const RedisDashboard = defineAsyncComponent(() => import("@/components/redis/Red
|
|||||||
const EtcdKeyBrowser = defineAsyncComponent(() => import("@/components/etcd/EtcdKeyBrowser.vue"));
|
const EtcdKeyBrowser = defineAsyncComponent(() => import("@/components/etcd/EtcdKeyBrowser.vue"));
|
||||||
const ZooKeeperKeyBrowser = defineAsyncComponent(() => import("@/components/zookeeper/ZooKeeperKeyBrowser.vue"));
|
const ZooKeeperKeyBrowser = defineAsyncComponent(() => import("@/components/zookeeper/ZooKeeperKeyBrowser.vue"));
|
||||||
const DocumentBrowser = defineAsyncComponent(() => import("@/components/document/DocumentBrowser.vue"));
|
const DocumentBrowser = defineAsyncComponent(() => import("@/components/document/DocumentBrowser.vue"));
|
||||||
|
const MongoGridFsBrowser = defineAsyncComponent(() => import("@/components/document/MongoGridFsBrowser.vue"));
|
||||||
|
const MongoBucketBrowser = defineAsyncComponent(() => import("@/components/document/MongoBucketBrowser.vue"));
|
||||||
const VectorBrowser = defineAsyncComponent(() => import("@/components/vector/VectorBrowser.vue"));
|
const VectorBrowser = defineAsyncComponent(() => import("@/components/vector/VectorBrowser.vue"));
|
||||||
const MqAdminConsole = defineAsyncComponent(() => import("@/components/mq/MqAdminConsole.vue"));
|
const MqAdminConsole = defineAsyncComponent(() => import("@/components/mq/MqAdminConsole.vue"));
|
||||||
const NacosAdminConsole = defineAsyncComponent(() => import("@/components/nacos/NacosAdminConsole.vue"));
|
const NacosAdminConsole = defineAsyncComponent(() => import("@/components/nacos/NacosAdminConsole.vue"));
|
||||||
@@ -1288,6 +1290,18 @@ defineExpose({ focusSearch, refreshData, handleModRTarget, requestQueryEditorExe
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<template v-else-if="activeTab.mode === 'mongo-gridfs'">
|
||||||
|
<div class="flex-1 min-h-0">
|
||||||
|
<MongoGridFsBrowser :key="activeTab.id" :connection-id="activeTab.connectionId" :database="activeTab.database" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-else-if="activeTab.mode === 'mongo-bucket'">
|
||||||
|
<div class="flex-1 min-h-0">
|
||||||
|
<MongoBucketBrowser :key="activeTab.id" :connection-id="activeTab.connectionId" :database="activeTab.database" :bucket="activeTab.mongoBucket?.bucketName || activeTab.sql" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
<!-- Vector mode: Qdrant and Milvus collections -->
|
<!-- Vector mode: Qdrant and Milvus collections -->
|
||||||
<template v-else-if="activeTab.mode === 'vector'">
|
<template v-else-if="activeTab.mode === 'vector'">
|
||||||
<div class="flex-1 min-h-0">
|
<div class="flex-1 min-h-0">
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ const SEARCH_SCOPE_TO_NODE_TYPES: Record<SearchScope, TreeNodeType[]> = {
|
|||||||
connection: ["connection"],
|
connection: ["connection"],
|
||||||
database: ["database", "redis-db", "mq-tenant", "nacos-namespace", "mongo-db"],
|
database: ["database", "redis-db", "mq-tenant", "nacos-namespace", "mongo-db"],
|
||||||
schema: ["schema"],
|
schema: ["schema"],
|
||||||
table: ["table", "mongo-collection", "vector-collection", "elasticsearch-index"],
|
table: ["table", "mongo-collection", "mongo-bucket", "vector-collection", "elasticsearch-index"],
|
||||||
view: ["view"],
|
view: ["view"],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ import {
|
|||||||
SquarePen,
|
SquarePen,
|
||||||
ListX,
|
ListX,
|
||||||
Info,
|
Info,
|
||||||
|
Archive,
|
||||||
} from "@lucide/vue";
|
} from "@lucide/vue";
|
||||||
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
|
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
|
||||||
import { useConnectionStore } from "@/stores/connectionStore";
|
import { useConnectionStore } from "@/stores/connectionStore";
|
||||||
@@ -76,7 +77,7 @@ import { clearActiveTableReferencePayload, createTableReferencePayload, createTa
|
|||||||
import { editableRowIdentifierColumns, usesSyntheticRowIdKey } from "@/lib/tableEditing";
|
import { editableRowIdentifierColumns, usesSyntheticRowIdKey } from "@/lib/tableEditing";
|
||||||
import { tableOpenPageLimit } from "@/lib/tableOpenPageLimit";
|
import { tableOpenPageLimit } from "@/lib/tableOpenPageLimit";
|
||||||
import { supportsDatabaseCreation, supportsDatabaseSearch, supportsFieldLineage, supportsObjectBrowserTreeNode, supportsSchemaDiagram, supportsSqlFileExecution, supportsTableImport, supportsTableTruncate, supportsTableStructureEditing, usesTreeSchemaMode } from "@/lib/databaseCapabilities";
|
import { supportsDatabaseCreation, supportsDatabaseSearch, supportsFieldLineage, supportsObjectBrowserTreeNode, supportsSchemaDiagram, supportsSqlFileExecution, supportsTableImport, supportsTableTruncate, supportsTableStructureEditing, usesTreeSchemaMode } from "@/lib/databaseCapabilities";
|
||||||
import { copyNameForTreeNode, objectSourceKindForTreeNode, shouldRunTreeNodeRowAction, sidebarSelectionCopyAction, treeNodeRowAction, treeNodeRowDoubleClickAction } from "@/lib/treeNodeClick";
|
import { copyNameForTreeNode, isDocumentBrowserTreeNode, objectSourceKindForTreeNode, shouldRunTreeNodeRowAction, sidebarSelectionCopyAction, treeNodeRowAction, treeNodeRowDoubleClickAction } from "@/lib/treeNodeClick";
|
||||||
import { formatSqlInsert } from "@/lib/exportFormats";
|
import { formatSqlInsert } from "@/lib/exportFormats";
|
||||||
import { joinExportedDdls } from "@/lib/ddlExport";
|
import { joinExportedDdls } from "@/lib/ddlExport";
|
||||||
import { fetchTableDataForExport } from "@/lib/tableDataExport";
|
import { fetchTableDataForExport } from "@/lib/tableDataExport";
|
||||||
@@ -315,6 +316,11 @@ function getIconInfo(node: TreeNode): { icon: any; colorClass: string } | null {
|
|||||||
return { icon: Database, colorClass: "text-blue-500" };
|
return { icon: Database, colorClass: "text-blue-500" };
|
||||||
case "mongo-db":
|
case "mongo-db":
|
||||||
return { icon: Database, colorClass: "text-yellow-500" };
|
return { icon: Database, colorClass: "text-yellow-500" };
|
||||||
|
case "mongo-gridfs":
|
||||||
|
case "mongo-buckets":
|
||||||
|
return { icon: Archive, colorClass: "text-amber-500" };
|
||||||
|
case "mongo-bucket":
|
||||||
|
return { icon: Archive, colorClass: "text-amber-400" };
|
||||||
case "mongo-collection":
|
case "mongo-collection":
|
||||||
return { icon: Table, colorClass: "text-green-400" };
|
return { icon: Table, colorClass: "text-green-400" };
|
||||||
case "vector-collection":
|
case "vector-collection":
|
||||||
@@ -648,12 +654,16 @@ function runRowClickAction(clickDetail: number) {
|
|||||||
void openObjectBrowser();
|
void openObjectBrowser();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (node.type === "mongo-gridfs") {
|
||||||
|
openMongoTreeData(node);
|
||||||
|
return;
|
||||||
|
}
|
||||||
const action = treeNodeRowAction(node.type, canExpand.value, settingsStore.editorSettings.sidebarActivation);
|
const action = treeNodeRowAction(node.type, canExpand.value, settingsStore.editorSettings.sidebarActivation);
|
||||||
if (!shouldRunTreeNodeRowAction(action, clickDetail)) return;
|
if (!shouldRunTreeNodeRowAction(action, clickDetail)) return;
|
||||||
if (action === "open-data") {
|
if (action === "open-data") {
|
||||||
openData();
|
openData();
|
||||||
} else if (node.type === "mongo-collection") {
|
} else if (isDocumentBrowserTreeNode(node.type)) {
|
||||||
openMongoCollectionData(node);
|
openMongoTreeData(node);
|
||||||
} else if (node.type === "procedure" || node.type === "function" || node.type === "sequence" || node.type === "package" || node.type === "package-body") {
|
} else if (node.type === "procedure" || node.type === "function" || node.type === "sequence" || node.type === "package" || node.type === "package-body") {
|
||||||
void viewObjectSource();
|
void viewObjectSource();
|
||||||
} else if (action === "toggle") {
|
} else if (action === "toggle") {
|
||||||
@@ -928,16 +938,25 @@ function onDoubleClick() {
|
|||||||
void viewObjectSource();
|
void viewObjectSource();
|
||||||
} else if (action === "open-saved-sql") {
|
} else if (action === "open-saved-sql") {
|
||||||
openSavedSqlFile();
|
openSavedSqlFile();
|
||||||
} else if (action === "toggle" && props.node.type === "mongo-collection") {
|
} else if (action === "toggle" && (props.node.type === "mongo-gridfs" || isDocumentBrowserTreeNode(props.node.type))) {
|
||||||
openMongoCollectionData(props.node);
|
openMongoTreeData(props.node);
|
||||||
} else if (action === "toggle") {
|
} else if (action === "toggle") {
|
||||||
toggle();
|
toggle();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function openMongoCollectionData(node: TreeNode) {
|
function openMongoTreeData(node: TreeNode) {
|
||||||
if (node.type !== "mongo-collection" || !node.connectionId || !node.database) return;
|
if (!node.connectionId || !node.database) return;
|
||||||
|
if (node.type === "mongo-gridfs") {
|
||||||
|
queryStore.openMongoGridFs(node.connectionId, node.database);
|
||||||
|
return;
|
||||||
|
}
|
||||||
const tabTitle = `${node.database}.${node.label}`;
|
const tabTitle = `${node.database}.${node.label}`;
|
||||||
|
if (node.type === "mongo-bucket") {
|
||||||
|
queryStore.openMongoBucket(node.connectionId, node.database, node.label);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (node.type !== "mongo-collection") return;
|
||||||
const tab = queryStore.createTab(node.connectionId, node.database, tabTitle, "mongo");
|
const tab = queryStore.createTab(node.connectionId, node.database, tabTitle, "mongo");
|
||||||
queryStore.updateSql(tab, node.label);
|
queryStore.updateSql(tab, node.label);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -510,6 +510,7 @@ export default {
|
|||||||
etcd: "etcd",
|
etcd: "etcd",
|
||||||
zookeeper: "ZooKeeper",
|
zookeeper: "ZooKeeper",
|
||||||
mongo: "Mongo",
|
mongo: "Mongo",
|
||||||
|
gridfs: "GridFS",
|
||||||
vector: "Vector",
|
vector: "Vector",
|
||||||
objects: "Objects",
|
objects: "Objects",
|
||||||
users: "Users & Privileges",
|
users: "Users & Privileges",
|
||||||
@@ -548,6 +549,37 @@ export default {
|
|||||||
fixedTabs: "Fixed tabs",
|
fixedTabs: "Fixed tabs",
|
||||||
openDataTabs: "Open tables",
|
openDataTabs: "Open tables",
|
||||||
},
|
},
|
||||||
|
gridfsBrowser: {
|
||||||
|
bucketCount: "buckets",
|
||||||
|
fileCount: "files",
|
||||||
|
name: "Name",
|
||||||
|
totalSize: "Size",
|
||||||
|
chunkSize: "Chunk Size",
|
||||||
|
uploadDate: "Upload Date",
|
||||||
|
contentType: "Content Type",
|
||||||
|
metadata: "Metadata",
|
||||||
|
selectBucket: "Select a GridFS bucket to inspect or open it.",
|
||||||
|
selectFile: "Select a GridFS file to inspect or manage it.",
|
||||||
|
emptyBuckets: "No GridFS buckets found. Create one to start storing files.",
|
||||||
|
emptyFiles: "This bucket has no files yet. Upload one to get started.",
|
||||||
|
createBucket: "New Bucket",
|
||||||
|
openBucket: "Open Bucket",
|
||||||
|
deleteBucket: "Delete Bucket",
|
||||||
|
createTitle: "Create GridFS Bucket",
|
||||||
|
deleteTitle: "Delete GridFS Bucket",
|
||||||
|
deleteMessage: "Delete the selected GridFS bucket and all files inside it?",
|
||||||
|
bucketName: "Bucket Name",
|
||||||
|
bucketNamePlaceholder: "example_bucket",
|
||||||
|
bucketCreated: "Bucket {bucket} created.",
|
||||||
|
bucketDeleted: "Bucket {bucket} deleted.",
|
||||||
|
uploadFile: "Upload File",
|
||||||
|
downloadFile: "Download File",
|
||||||
|
deleteFile: "Delete File",
|
||||||
|
deleteFileTitle: "Delete GridFS File",
|
||||||
|
deleteFileMessage: "Delete the selected file from this GridFS bucket?",
|
||||||
|
fileUploaded: "Uploaded {fileName}.",
|
||||||
|
fileDeleted: "Deleted {fileName}.",
|
||||||
|
},
|
||||||
executionSummary: {
|
executionSummary: {
|
||||||
empty: "No execution summary",
|
empty: "No execution summary",
|
||||||
executing: "Executing...",
|
executing: "Executing...",
|
||||||
@@ -1485,6 +1517,8 @@ export default {
|
|||||||
functions: "Functions",
|
functions: "Functions",
|
||||||
sequences: "Sequences",
|
sequences: "Sequences",
|
||||||
packages: "Packages",
|
packages: "Packages",
|
||||||
|
gridfs: "GridFS",
|
||||||
|
buckets: "Buckets",
|
||||||
partitions: "Partitions",
|
partitions: "Partitions",
|
||||||
loadMore: "Load more...",
|
loadMore: "Load more...",
|
||||||
objectBrowser: "Browse in Object Browser ({count})",
|
objectBrowser: "Browse in Object Browser ({count})",
|
||||||
|
|||||||
@@ -550,6 +550,7 @@ export default withEnglishFallback({
|
|||||||
openTabs: "Pestañas abiertas",
|
openTabs: "Pestañas abiertas",
|
||||||
fixedTabs: "Pestañas fijadas",
|
fixedTabs: "Pestañas fijadas",
|
||||||
openDataTabs: "Tablas abiertas",
|
openDataTabs: "Tablas abiertas",
|
||||||
|
gridfs: "GridFS",
|
||||||
},
|
},
|
||||||
executionSummary: {
|
executionSummary: {
|
||||||
empty: "Sin resumen de ejecución",
|
empty: "Sin resumen de ejecución",
|
||||||
@@ -3215,4 +3216,35 @@ export default withEnglishFallback({
|
|||||||
test: "Probar",
|
test: "Probar",
|
||||||
readOnly: "Solo lectura",
|
readOnly: "Solo lectura",
|
||||||
},
|
},
|
||||||
|
gridfsBrowser: {
|
||||||
|
bucketCount: "Cantidad de buckets",
|
||||||
|
fileCount: "Archivos",
|
||||||
|
name: "Nombre",
|
||||||
|
totalSize: "Tamaño",
|
||||||
|
chunkSize: "Tamaño de fragmento",
|
||||||
|
uploadDate: "Fecha de carga",
|
||||||
|
contentType: "Tipo de contenido",
|
||||||
|
metadata: "Metadatos",
|
||||||
|
selectBucket: "Selecciona un bucket de GridFS para ver o abrir.",
|
||||||
|
selectFile: "Selecciona un archivo de GridFS para ver o administrar.",
|
||||||
|
emptyBuckets: "Actualmente no hay buckets de GridFS, puedes crear uno nuevo.",
|
||||||
|
emptyFiles: "El bucket actual aún no tiene archivos, puedes subir uno primero.",
|
||||||
|
createBucket: "Crear bucket",
|
||||||
|
openBucket: "Abrir bucket",
|
||||||
|
deleteBucket: "Eliminar bucket",
|
||||||
|
createTitle: "Crear bucket de GridFS",
|
||||||
|
deleteTitle: "Eliminar bucket de GridFS",
|
||||||
|
deleteMessage: "¿Estás seguro de eliminar el bucket de GridFS seleccionado y todos los archivos que contiene?",
|
||||||
|
bucketName: "Nombre del bucket",
|
||||||
|
bucketNamePlaceholder: "example_bucket",
|
||||||
|
bucketCreated: "Bucket {bucket} creado.",
|
||||||
|
bucketDeleted: "Bucket {bucket} eliminado.",
|
||||||
|
uploadFile: "Subir archivo",
|
||||||
|
downloadFile: "Descargar archivo",
|
||||||
|
deleteFile: "Eliminar archivo",
|
||||||
|
deleteFileTitle: "Eliminar archivo de GridFS",
|
||||||
|
deleteFileMessage: "¿Estás seguro de eliminar el archivo seleccionado del bucket de GridFS actual?",
|
||||||
|
fileUploaded: "Archivo {fileName} subido.",
|
||||||
|
fileDeleted: "Archivo {fileName} eliminado.",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
@@ -548,6 +548,7 @@ export default withEnglishFallback({
|
|||||||
openTabs: "Schede aperte",
|
openTabs: "Schede aperte",
|
||||||
fixedTabs: "Schede bloccate",
|
fixedTabs: "Schede bloccate",
|
||||||
openDataTabs: "Tabelle aperte",
|
openDataTabs: "Tabelle aperte",
|
||||||
|
gridfs: "GridFS",
|
||||||
},
|
},
|
||||||
executionSummary: {
|
executionSummary: {
|
||||||
empty: "Nessun riepilogo esecuzione",
|
empty: "Nessun riepilogo esecuzione",
|
||||||
@@ -3213,4 +3214,35 @@ export default withEnglishFallback({
|
|||||||
test: "Test",
|
test: "Test",
|
||||||
readOnly: "Sola lettura",
|
readOnly: "Sola lettura",
|
||||||
},
|
},
|
||||||
|
gridfsBrowser: {
|
||||||
|
bucketCount: "Bucket",
|
||||||
|
fileCount: "File",
|
||||||
|
name: "Nome",
|
||||||
|
totalSize: "Dimensione",
|
||||||
|
chunkSize: "Dimensione chunk",
|
||||||
|
uploadDate: "Data di caricamento",
|
||||||
|
contentType: "Tipo di contenuto",
|
||||||
|
metadata: "Metadati",
|
||||||
|
selectBucket: "Seleziona un bucket GridFS per visualizzarlo o aprirlo.",
|
||||||
|
selectFile: "Seleziona un file GridFS per visualizzarlo o gestirlo.",
|
||||||
|
emptyBuckets: "Nessun bucket GridFS presente. Puoi crearne uno nuovo.",
|
||||||
|
emptyFiles: "Il bucket attuale non contiene file. Puoi caricarne uno.",
|
||||||
|
createBucket: "Crea bucket",
|
||||||
|
openBucket: "Apri bucket",
|
||||||
|
deleteBucket: "Elimina bucket",
|
||||||
|
createTitle: "Crea bucket GridFS",
|
||||||
|
deleteTitle: "Elimina bucket GridFS",
|
||||||
|
deleteMessage: "Sei sicuro di voler eliminare il bucket GridFS selezionato e tutti i file in esso contenuti?",
|
||||||
|
bucketName: "Nome bucket",
|
||||||
|
bucketNamePlaceholder: "example_bucket",
|
||||||
|
bucketCreated: "Bucket {bucket} creato.",
|
||||||
|
bucketDeleted: "Bucket {bucket} eliminato.",
|
||||||
|
uploadFile: "Carica file",
|
||||||
|
downloadFile: "Scarica file",
|
||||||
|
deleteFile: "Elimina file",
|
||||||
|
deleteFileTitle: "Elimina file GridFS",
|
||||||
|
deleteFileMessage: "Sei sicuro di voler eliminare il file selezionato dal bucket GridFS corrente?",
|
||||||
|
fileUploaded: "{fileName} caricato.",
|
||||||
|
fileDeleted: "{fileName} eliminato.",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
@@ -548,6 +548,7 @@ export default withEnglishFallback({
|
|||||||
openDataTabs: "開いているテーブル",
|
openDataTabs: "開いているテーブル",
|
||||||
zookeeper: "ZooKeeper",
|
zookeeper: "ZooKeeper",
|
||||||
vector: "ベクター",
|
vector: "ベクター",
|
||||||
|
gridfs: "GridFS",
|
||||||
},
|
},
|
||||||
executionSummary: {
|
executionSummary: {
|
||||||
empty: "実行サマリーはありません",
|
empty: "実行サマリーはありません",
|
||||||
@@ -3213,4 +3214,35 @@ export default withEnglishFallback({
|
|||||||
namespaceDesc: "説明",
|
namespaceDesc: "説明",
|
||||||
namespaceDescPlaceholder: "デフォルトは名前空間名",
|
namespaceDescPlaceholder: "デフォルトは名前空間名",
|
||||||
},
|
},
|
||||||
|
gridfsBrowser: {
|
||||||
|
bucketCount: "バケット",
|
||||||
|
fileCount: "ファイル",
|
||||||
|
name: "名前",
|
||||||
|
totalSize: "サイズ",
|
||||||
|
chunkSize: "チャンクサイズ",
|
||||||
|
uploadDate: "アップロード日",
|
||||||
|
contentType: "コンテンツタイプ",
|
||||||
|
metadata: "メタデータ",
|
||||||
|
selectBucket: "GridFS バケットを選択して表示または開きます。",
|
||||||
|
selectFile: "GridFS ファイルを選択して表示または管理します。",
|
||||||
|
emptyBuckets: "現在 GridFS バケットがありません。新しく作成できます。",
|
||||||
|
emptyFiles: "現在のバケットにはファイルがありません。アップロードできます。",
|
||||||
|
createBucket: "バケットを新規作成",
|
||||||
|
openBucket: "バケットを開く",
|
||||||
|
deleteBucket: "バケットを削除",
|
||||||
|
createTitle: "新規 GridFS バケット作成",
|
||||||
|
deleteTitle: "GridFS バケットの削除",
|
||||||
|
deleteMessage: "選択した GridFS バケットとその中のすべてのファイルを削除してもよろしいですか?",
|
||||||
|
bucketName: "バケット名",
|
||||||
|
bucketNamePlaceholder: "example_bucket",
|
||||||
|
bucketCreated: "バケット {bucket} を作成しました。",
|
||||||
|
bucketDeleted: "バケット {bucket} を削除しました。",
|
||||||
|
uploadFile: "ファイルをアップロード",
|
||||||
|
downloadFile: "ファイルをダウンロード",
|
||||||
|
deleteFile: "ファイルを削除",
|
||||||
|
deleteFileTitle: "GridFS ファイルの削除",
|
||||||
|
deleteFileMessage: "現在の GridFS バケットから選択したファイルを削除してもよろしいですか?",
|
||||||
|
fileUploaded: "{fileName} をアップロードしました。",
|
||||||
|
fileDeleted: "{fileName} を削除しました。",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
@@ -549,6 +549,7 @@ export default withEnglishFallback({
|
|||||||
openTabs: "Abas abertas",
|
openTabs: "Abas abertas",
|
||||||
fixedTabs: "Abas fixadas",
|
fixedTabs: "Abas fixadas",
|
||||||
openDataTabs: "Tabelas abertas",
|
openDataTabs: "Tabelas abertas",
|
||||||
|
gridfs: "GridFS",
|
||||||
},
|
},
|
||||||
executionSummary: {
|
executionSummary: {
|
||||||
empty: "Nenhum resumo de execução",
|
empty: "Nenhum resumo de execução",
|
||||||
@@ -3214,4 +3215,35 @@ export default withEnglishFallback({
|
|||||||
test: "Testar",
|
test: "Testar",
|
||||||
readOnly: "Somente leitura",
|
readOnly: "Somente leitura",
|
||||||
},
|
},
|
||||||
|
gridfsBrowser: {
|
||||||
|
bucketCount: "Buckets",
|
||||||
|
fileCount: "Arquivos",
|
||||||
|
name: "Nome",
|
||||||
|
totalSize: "Tamanho",
|
||||||
|
chunkSize: "Tamanho do chunk",
|
||||||
|
uploadDate: "Data de upload",
|
||||||
|
contentType: "Tipo de conteúdo",
|
||||||
|
metadata: "Metadados",
|
||||||
|
selectBucket: "Selecione um bucket GridFS para visualizar ou abrir.",
|
||||||
|
selectFile: "Selecione um arquivo GridFS para visualizar ou gerenciar.",
|
||||||
|
emptyBuckets: "Nenhum bucket GridFS no momento. Você pode criar um.",
|
||||||
|
emptyFiles: "O bucket atual ainda não tem arquivos. Você pode fazer upload de um.",
|
||||||
|
createBucket: "Criar bucket",
|
||||||
|
openBucket: "Abrir bucket",
|
||||||
|
deleteBucket: "Excluir bucket",
|
||||||
|
createTitle: "Criar bucket GridFS",
|
||||||
|
deleteTitle: "Excluir bucket GridFS",
|
||||||
|
deleteMessage: "Tem certeza de que deseja excluir o bucket GridFS selecionado e todos os seus arquivos?",
|
||||||
|
bucketName: "Nome do bucket",
|
||||||
|
bucketNamePlaceholder: "example_bucket",
|
||||||
|
bucketCreated: "Bucket {bucket} criado.",
|
||||||
|
bucketDeleted: "Bucket {bucket} excluído.",
|
||||||
|
uploadFile: "Fazer upload de arquivo",
|
||||||
|
downloadFile: "Baixar arquivo",
|
||||||
|
deleteFile: "Excluir arquivo",
|
||||||
|
deleteFileTitle: "Excluir arquivo GridFS",
|
||||||
|
deleteFileMessage: "Tem certeza de que deseja excluir o arquivo selecionado do bucket GridFS atual?",
|
||||||
|
fileUploaded: "Arquivo {fileName} enviado.",
|
||||||
|
fileDeleted: "Arquivo {fileName} excluído.",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
@@ -512,6 +512,7 @@ export default withEnglishFallback({
|
|||||||
etcd: "etcd",
|
etcd: "etcd",
|
||||||
zookeeper: "ZooKeeper",
|
zookeeper: "ZooKeeper",
|
||||||
mongo: "Mongo",
|
mongo: "Mongo",
|
||||||
|
gridfs: "GridFS",
|
||||||
vector: "向量",
|
vector: "向量",
|
||||||
objects: "对象",
|
objects: "对象",
|
||||||
users: "用户与权限",
|
users: "用户与权限",
|
||||||
@@ -550,6 +551,37 @@ export default withEnglishFallback({
|
|||||||
fixedTabs: "固定标签页",
|
fixedTabs: "固定标签页",
|
||||||
openDataTabs: "已打开的数据表",
|
openDataTabs: "已打开的数据表",
|
||||||
},
|
},
|
||||||
|
gridfsBrowser: {
|
||||||
|
bucketCount: "\u5b58\u50a8\u6876",
|
||||||
|
fileCount: "\u6587\u4ef6",
|
||||||
|
name: "\u540d\u79f0",
|
||||||
|
totalSize: "\u5927\u5c0f",
|
||||||
|
chunkSize: "\u5757\u5927\u5c0f",
|
||||||
|
uploadDate: "\u4e0a\u4f20\u65e5\u671f",
|
||||||
|
contentType: "\u5185\u5bb9\u7c7b\u578b",
|
||||||
|
metadata: "\u5143\u6570\u636e",
|
||||||
|
selectBucket: "\u9009\u62e9\u4e00\u4e2a GridFS \u5b58\u50a8\u6876\u4ee5\u67e5\u770b\u6216\u6253\u5f00\u3002",
|
||||||
|
selectFile: "\u9009\u62e9\u4e00\u4e2a GridFS \u6587\u4ef6\u4ee5\u67e5\u770b\u6216\u7ba1\u7406\u3002",
|
||||||
|
emptyBuckets: "\u5f53\u524d\u6ca1\u6709 GridFS \u5b58\u50a8\u6876\uff0c\u53ef\u4ee5\u5148\u65b0\u5efa\u4e00\u4e2a\u3002",
|
||||||
|
emptyFiles: "\u5f53\u524d\u5b58\u50a8\u6876\u8fd8\u6ca1\u6709\u6587\u4ef6\uff0c\u53ef\u4ee5\u5148\u4e0a\u4f20\u4e00\u4e2a\u3002",
|
||||||
|
createBucket: "\u65b0\u5efa\u5b58\u50a8\u6876",
|
||||||
|
openBucket: "\u6253\u5f00\u5b58\u50a8\u6876",
|
||||||
|
deleteBucket: "\u5220\u9664\u5b58\u50a8\u6876",
|
||||||
|
createTitle: "\u65b0\u5efa GridFS \u5b58\u50a8\u6876",
|
||||||
|
deleteTitle: "\u5220\u9664 GridFS \u5b58\u50a8\u6876",
|
||||||
|
deleteMessage: "\u786e\u5b9a\u5220\u9664\u9009\u4e2d\u7684 GridFS \u5b58\u50a8\u6876\u53ca\u5176\u4e2d\u7684\u6240\u6709\u6587\u4ef6\u5417\uff1f",
|
||||||
|
bucketName: "\u5b58\u50a8\u6876\u540d\u79f0",
|
||||||
|
bucketNamePlaceholder: "example_bucket",
|
||||||
|
bucketCreated: "\u5df2\u521b\u5efa\u5b58\u50a8\u6876 {bucket}\u3002",
|
||||||
|
bucketDeleted: "\u5df2\u5220\u9664\u5b58\u50a8\u6876 {bucket}\u3002",
|
||||||
|
uploadFile: "\u4e0a\u4f20\u6587\u4ef6",
|
||||||
|
downloadFile: "\u4e0b\u8f7d\u6587\u4ef6",
|
||||||
|
deleteFile: "\u5220\u9664\u6587\u4ef6",
|
||||||
|
deleteFileTitle: "\u5220\u9664 GridFS \u6587\u4ef6",
|
||||||
|
deleteFileMessage: "\u786e\u5b9a\u4ece\u5f53\u524d GridFS \u5b58\u50a8\u6876\u4e2d\u5220\u9664\u9009\u4e2d\u6587\u4ef6\u5417\uff1f",
|
||||||
|
fileUploaded: "\u5df2\u4e0a\u4f20 {fileName}\u3002",
|
||||||
|
fileDeleted: "\u5df2\u5220\u9664 {fileName}\u3002",
|
||||||
|
},
|
||||||
executionSummary: {
|
executionSummary: {
|
||||||
empty: "暂无执行摘要",
|
empty: "暂无执行摘要",
|
||||||
executing: "正在执行...",
|
executing: "正在执行...",
|
||||||
|
|||||||
@@ -549,6 +549,7 @@ export default withEnglishFallback({
|
|||||||
openTabs: "已開啟的分頁",
|
openTabs: "已開啟的分頁",
|
||||||
fixedTabs: "固定分頁",
|
fixedTabs: "固定分頁",
|
||||||
openDataTabs: "已開啟的資料表",
|
openDataTabs: "已開啟的資料表",
|
||||||
|
gridfs: "GridFS",
|
||||||
},
|
},
|
||||||
executionSummary: {
|
executionSummary: {
|
||||||
empty: "無執行摘要",
|
empty: "無執行摘要",
|
||||||
@@ -3214,4 +3215,35 @@ export default withEnglishFallback({
|
|||||||
summaryLease: "租約",
|
summaryLease: "租約",
|
||||||
summarySize: "大小",
|
summarySize: "大小",
|
||||||
},
|
},
|
||||||
|
gridfsBrowser: {
|
||||||
|
bucketCount: "儲存桶",
|
||||||
|
fileCount: "檔案",
|
||||||
|
name: "名稱",
|
||||||
|
totalSize: "大小",
|
||||||
|
chunkSize: "區塊大小",
|
||||||
|
uploadDate: "上傳日期",
|
||||||
|
contentType: "內容類型",
|
||||||
|
metadata: "元資料",
|
||||||
|
selectBucket: "選擇一個 GridFS 儲存桶以查看或開啟。",
|
||||||
|
selectFile: "選擇一個 GridFS 檔案以查看或管理。",
|
||||||
|
emptyBuckets: "目前沒有 GridFS 儲存桶,可以先新增一個。",
|
||||||
|
emptyFiles: "目前儲存桶還沒有檔案,可以先上傳一個。",
|
||||||
|
createBucket: "新增儲存桶",
|
||||||
|
openBucket: "開啟儲存桶",
|
||||||
|
deleteBucket: "刪除儲存桶",
|
||||||
|
createTitle: "新增 GridFS 儲存桶",
|
||||||
|
deleteTitle: "刪除 GridFS 儲存桶",
|
||||||
|
deleteMessage: "確定刪除選中的 GridFS 儲存桶及其中的所有檔案嗎?",
|
||||||
|
bucketName: "儲存桶名稱",
|
||||||
|
bucketNamePlaceholder: "example_bucket",
|
||||||
|
bucketCreated: "已建立儲存桶 {bucket}。",
|
||||||
|
bucketDeleted: "已刪除儲存桶 {bucket}。",
|
||||||
|
uploadFile: "上傳檔案",
|
||||||
|
downloadFile: "下載檔案",
|
||||||
|
deleteFile: "刪除檔案",
|
||||||
|
deleteFileTitle: "刪除 GridFS 檔案",
|
||||||
|
deleteFileMessage: "確定從目前 GridFS 儲存桶中刪除選中檔案嗎?",
|
||||||
|
fileUploaded: "已上傳 {fileName}。",
|
||||||
|
fileDeleted: "已刪除 {fileName}。",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
@@ -375,6 +375,13 @@ export const documentListDatabases = forward("documentListDatabases");
|
|||||||
export const mongoListDatabases = forward("mongoListDatabases");
|
export const mongoListDatabases = forward("mongoListDatabases");
|
||||||
export const documentListCollections = forward("documentListCollections");
|
export const documentListCollections = forward("documentListCollections");
|
||||||
export const mongoListCollections = forward("mongoListCollections");
|
export const mongoListCollections = forward("mongoListCollections");
|
||||||
|
export const documentListGridFsBuckets = forward("documentListGridFsBuckets");
|
||||||
|
export const documentCreateGridFsBucket = forward("documentCreateGridFsBucket");
|
||||||
|
export const documentDeleteGridFsBucket = forward("documentDeleteGridFsBucket");
|
||||||
|
export const documentListGridFsFiles = forward("documentListGridFsFiles");
|
||||||
|
export const documentDownloadGridFsFile = forward("documentDownloadGridFsFile");
|
||||||
|
export const documentUploadGridFsFile = forward("documentUploadGridFsFile");
|
||||||
|
export const documentDeleteGridFsFile = forward("documentDeleteGridFsFile");
|
||||||
export const vectorGetCollectionDetail = forward("vectorGetCollectionDetail");
|
export const vectorGetCollectionDetail = forward("vectorGetCollectionDetail");
|
||||||
export const mongoCreateDatabase = forward("mongoCreateDatabase");
|
export const mongoCreateDatabase = forward("mongoCreateDatabase");
|
||||||
export const mongoDropDatabase = forward("mongoDropDatabase");
|
export const mongoDropDatabase = forward("mongoDropDatabase");
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ import type {
|
|||||||
KvPutResponse,
|
KvPutResponse,
|
||||||
KvDeleteResponse,
|
KvDeleteResponse,
|
||||||
MongoDocumentResult,
|
MongoDocumentResult,
|
||||||
|
MongoGridFsBucketInfo,
|
||||||
HistoryEntry,
|
HistoryEntry,
|
||||||
SqlFileRequest,
|
SqlFileRequest,
|
||||||
SqlFilePreview,
|
SqlFilePreview,
|
||||||
@@ -88,6 +89,7 @@ import type {
|
|||||||
BuildExplainSqlOptions,
|
BuildExplainSqlOptions,
|
||||||
ExplainSqlBuildResult,
|
ExplainSqlBuildResult,
|
||||||
DroppedFilePreviewSqlOptions,
|
DroppedFilePreviewSqlOptions,
|
||||||
|
MongoGridFsFileInfo,
|
||||||
} from "./tauri";
|
} from "./tauri";
|
||||||
import type { QueryEditability } from "@/lib/sqlAnalysis";
|
import type { QueryEditability } from "@/lib/sqlAnalysis";
|
||||||
import type {
|
import type {
|
||||||
@@ -1800,6 +1802,55 @@ export async function documentFindDocuments(connectionId: string, database: stri
|
|||||||
return post("/api/document-store/find-documents", { connectionId, database, collection, skip, limit, filter, projection, sort, executionId });
|
return post("/api/document-store/find-documents", { connectionId, database, collection, skip, limit, filter, projection, sort, executionId });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function documentListGridFsFiles(connectionId: string, database: string, bucket: string): Promise<MongoGridFsFileInfo[]> {
|
||||||
|
return post("/api/document-store/list-gridfs-files", { connectionId, database, bucket });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentListGridFsBuckets(connectionId: string, database: string): Promise<MongoGridFsBucketInfo[]> {
|
||||||
|
return post("/api/document-store/list-gridfs-buckets", { connectionId, database });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentCreateGridFsBucket(connectionId: string, database: string, bucket: string): Promise<void> {
|
||||||
|
return post("/api/document-store/create-gridfs-bucket", { connectionId, database, bucket });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentDeleteGridFsBucket(connectionId: string, database: string, bucket: string): Promise<void> {
|
||||||
|
return post("/api/document-store/delete-gridfs-bucket", { connectionId, database, bucket });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentDownloadGridFsFile(connectionId: string, database: string, bucket: string, fileId: string): Promise<Uint8Array> {
|
||||||
|
const res = await fetch(apiUrl("/api/document-store/download-gridfs-file"), {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ connectionId, database, bucket, fileId }),
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error(await res.text());
|
||||||
|
const data = (await res.json()) as number[];
|
||||||
|
return new Uint8Array(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentUploadGridFsFile(connectionId: string, database: string, bucket: string, fileName: string, data: Uint8Array, contentType?: string): Promise<string> {
|
||||||
|
const body = new FormData();
|
||||||
|
body.append("connectionId", connectionId);
|
||||||
|
body.append("database", database);
|
||||||
|
body.append("bucket", bucket);
|
||||||
|
body.append("fileName", fileName);
|
||||||
|
if (contentType) body.append("contentType", contentType);
|
||||||
|
const bytes = new Uint8Array(data.byteLength);
|
||||||
|
bytes.set(data);
|
||||||
|
body.append("file", new Blob([bytes], { type: contentType || "application/octet-stream" }), fileName);
|
||||||
|
const res = await fetch(apiUrl("/api/document-store/upload-gridfs-file"), {
|
||||||
|
method: "POST",
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error(await res.text());
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentDeleteGridFsFile(connectionId: string, database: string, bucket: string, fileId: string): Promise<void> {
|
||||||
|
return post("/api/document-store/delete-gridfs-file", { connectionId, database, bucket, fileId });
|
||||||
|
}
|
||||||
|
|
||||||
export async function mongoServerVersion(connectionId: string, database: string, executionId?: string): Promise<string> {
|
export async function mongoServerVersion(connectionId: string, database: string, executionId?: string): Promise<string> {
|
||||||
return post("/api/mongo/server-version", { connectionId, database, executionId });
|
return post("/api/mongo/server-version", { connectionId, database, executionId });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ export type ActiveTabSidebarTarget =
|
|||||||
database: string;
|
database: string;
|
||||||
collectionName: string;
|
collectionName: string;
|
||||||
}
|
}
|
||||||
|
| {
|
||||||
|
type: "mongo-gridfs";
|
||||||
|
connectionId: string;
|
||||||
|
database: string;
|
||||||
|
}
|
||||||
| {
|
| {
|
||||||
type: "vector-collection";
|
type: "vector-collection";
|
||||||
connectionId: string;
|
connectionId: string;
|
||||||
@@ -75,6 +80,22 @@ export function activeTabSidebarTarget(tab: QueryTab | undefined | null): Active
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (tab.mode === "mongo-bucket") {
|
||||||
|
return {
|
||||||
|
type: "mongo-gridfs",
|
||||||
|
connectionId: tab.connectionId,
|
||||||
|
database: tab.database,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tab.mode === "mongo-gridfs") {
|
||||||
|
return {
|
||||||
|
type: "mongo-gridfs",
|
||||||
|
connectionId: tab.connectionId,
|
||||||
|
database: tab.database,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (tab.mode === "vector") {
|
if (tab.mode === "vector") {
|
||||||
const collectionName = tab.sql || tab.title;
|
const collectionName = tab.sql || tab.title;
|
||||||
if (!collectionName) return null;
|
if (!collectionName) return null;
|
||||||
@@ -131,6 +152,10 @@ export function matchesTarget(node: TreeNode, target: ActiveTabSidebarTarget): b
|
|||||||
return node.type === "mongo-collection" && node.connectionId === target.connectionId && node.database === target.database && node.label === target.collectionName;
|
return node.type === "mongo-collection" && node.connectionId === target.connectionId && node.database === target.database && node.label === target.collectionName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (target.type === "mongo-gridfs") {
|
||||||
|
return node.type === "mongo-gridfs" && node.connectionId === target.connectionId && node.database === target.database;
|
||||||
|
}
|
||||||
|
|
||||||
if (target.type === "vector-collection") {
|
if (target.type === "vector-collection") {
|
||||||
return node.type === "vector-collection" && node.connectionId === target.connectionId && node.label === target.collectionName;
|
return node.type === "vector-collection" && node.connectionId === target.connectionId && node.label === target.collectionName;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,12 @@ export function sortSidebarTreeChildrenForParent(parent: Pick<TreeNode, "type">,
|
|||||||
const normalized = children.map((child) => sortRecursive(child, databaseType));
|
const normalized = children.map((child) => sortRecursive(child, databaseType));
|
||||||
|
|
||||||
if (parent.type === "mongo-db") {
|
if (parent.type === "mongo-db") {
|
||||||
|
const gridFsNodes = normalized.filter((child) => child.type === "mongo-gridfs");
|
||||||
|
const collections = normalized.filter((child) => child.type !== "mongo-gridfs");
|
||||||
|
return [...gridFsNodes, ...sortByLabel(collections)];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parent.type === "mongo-buckets") {
|
||||||
return sortByLabel(normalized);
|
return sortByLabel(normalized);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,28 @@
|
|||||||
import type { TreeNodeType } from "@/types/database";
|
import type { TreeNodeType } from "@/types/database";
|
||||||
|
|
||||||
const leafTypes: Set<TreeNodeType> = new Set(["column", "index", "fkey", "trigger", "procedure", "function", "package", "package-body", "object-browser", "redis-db", "mq-tenant", "zookeeper-root", "vector-collection", "elasticsearch-index", "user-admin", "saved-sql-file", "load-more"]);
|
const leafTypes: Set<TreeNodeType> = new Set([
|
||||||
|
"column",
|
||||||
|
"index",
|
||||||
|
"fkey",
|
||||||
|
"trigger",
|
||||||
|
"procedure",
|
||||||
|
"function",
|
||||||
|
"package",
|
||||||
|
"package-body",
|
||||||
|
"object-browser",
|
||||||
|
"redis-db",
|
||||||
|
"mq-tenant",
|
||||||
|
"zookeeper-root",
|
||||||
|
"mongo-gridfs",
|
||||||
|
"mongo-bucket",
|
||||||
|
"vector-collection",
|
||||||
|
"elasticsearch-index",
|
||||||
|
"user-admin",
|
||||||
|
"saved-sql-file",
|
||||||
|
"load-more",
|
||||||
|
]);
|
||||||
|
|
||||||
const fullWidthLabelTypes: Set<TreeNodeType> = new Set(["table", "view", "materialized_view", "mongo-collection", "vector-collection", "elasticsearch-index"]);
|
const fullWidthLabelTypes: Set<TreeNodeType> = new Set(["table", "view", "materialized_view", "mongo-collection", "mongo-bucket", "vector-collection", "elasticsearch-index"]);
|
||||||
|
|
||||||
const emptyContainerTypes: Set<TreeNodeType> = new Set(["saved-sql-root", "saved-sql-folder"]);
|
const emptyContainerTypes: Set<TreeNodeType> = new Set(["saved-sql-root", "saved-sql-folder"]);
|
||||||
|
|
||||||
@@ -18,6 +38,8 @@ const pinnableTypes: Set<TreeNodeType> = new Set([
|
|||||||
"materialized_view",
|
"materialized_view",
|
||||||
"redis-db",
|
"redis-db",
|
||||||
"mongo-db",
|
"mongo-db",
|
||||||
|
"mongo-gridfs",
|
||||||
|
"mongo-bucket",
|
||||||
"mongo-collection",
|
"mongo-collection",
|
||||||
"vector-collection",
|
"vector-collection",
|
||||||
"elasticsearch-index",
|
"elasticsearch-index",
|
||||||
|
|||||||
@@ -70,6 +70,15 @@ export function tabDisplayTitle(tab: QueryTab, t: Translate): string {
|
|||||||
if (compact) return tab.sql;
|
if (compact) return tab.sql;
|
||||||
return `${tab.sql}@${database}`;
|
return `${tab.sql}@${database}`;
|
||||||
}
|
}
|
||||||
|
if (tab.mode === "mongo-gridfs") {
|
||||||
|
if (compact) return t("tabs.gridfs");
|
||||||
|
return `${t("tabs.gridfs")}@${database}`;
|
||||||
|
}
|
||||||
|
if (tab.mode === "mongo-bucket") {
|
||||||
|
const bucketName = tab.mongoBucket?.bucketName || tab.sql || tab.title.split(".").pop() || tab.title;
|
||||||
|
if (compact) return bucketName;
|
||||||
|
return `${bucketName}@${database}`;
|
||||||
|
}
|
||||||
if (tab.mode === "vector" && tab.sql) {
|
if (tab.mode === "vector" && tab.sql) {
|
||||||
if (compact) return tab.sql;
|
if (compact) return tab.sql;
|
||||||
return `${tab.sql}@${database}`;
|
return `${tab.sql}@${database}`;
|
||||||
@@ -114,6 +123,12 @@ export function tabTooltipLines(tab: QueryTab, t: Translate): { label: string; v
|
|||||||
if (tab.mode === "mongo" && tab.sql) {
|
if (tab.mode === "mongo" && tab.sql) {
|
||||||
lines.push({ label: t("tabs.tooltipCollection"), value: tab.sql });
|
lines.push({ label: t("tabs.tooltipCollection"), value: tab.sql });
|
||||||
}
|
}
|
||||||
|
if (tab.mode === "mongo-gridfs") {
|
||||||
|
lines.push({ label: t("tabs.gridfs"), value: t("tabs.gridfs") });
|
||||||
|
}
|
||||||
|
if (tab.mode === "mongo-bucket") {
|
||||||
|
lines.push({ label: t("tabs.gridfs"), value: tab.mongoBucket?.bucketName || tab.sql || tab.title });
|
||||||
|
}
|
||||||
if (tab.mode === "vector" && tab.sql) {
|
if (tab.mode === "vector" && tab.sql) {
|
||||||
lines.push({ label: t("tabs.tooltipCollection"), value: tab.sql });
|
lines.push({ label: t("tabs.tooltipCollection"), value: tab.sql });
|
||||||
}
|
}
|
||||||
@@ -182,6 +197,7 @@ export function tabModeLabel(tab: QueryTab, t: Translate): string {
|
|||||||
if (tab.mode === "data") return t("tabs.table");
|
if (tab.mode === "data") return t("tabs.table");
|
||||||
if (tab.mode === "query") return t("tabs.sql");
|
if (tab.mode === "query") return t("tabs.sql");
|
||||||
if (tab.mode === "mongo") return t("tabs.mongo");
|
if (tab.mode === "mongo") return t("tabs.mongo");
|
||||||
|
if (tab.mode === "mongo-gridfs" || tab.mode === "mongo-bucket") return t("tabs.gridfs");
|
||||||
if (tab.mode === "vector") return t("tabs.vector");
|
if (tab.mode === "vector") return t("tabs.vector");
|
||||||
if (tab.mode === "redis") return t("tabs.redis");
|
if (tab.mode === "redis") return t("tabs.redis");
|
||||||
if (tab.mode === "etcd") return t("tabs.etcd");
|
if (tab.mode === "etcd") return t("tabs.etcd");
|
||||||
|
|||||||
@@ -1484,6 +1484,24 @@ export interface MongoDocumentResult {
|
|||||||
total: number;
|
total: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface MongoGridFsFileInfo {
|
||||||
|
id: string;
|
||||||
|
filename?: string;
|
||||||
|
length: number;
|
||||||
|
chunkSize: number;
|
||||||
|
uploadDate?: string;
|
||||||
|
metadata?: any;
|
||||||
|
md5?: string;
|
||||||
|
contentType?: string;
|
||||||
|
aliases?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MongoGridFsBucketInfo {
|
||||||
|
name: string;
|
||||||
|
fileCount: number;
|
||||||
|
totalBytes: number;
|
||||||
|
}
|
||||||
|
|
||||||
export async function documentListDatabases(connectionId: string): Promise<string[]> {
|
export async function documentListDatabases(connectionId: string): Promise<string[]> {
|
||||||
return invoke("document_list_databases", { connectionId });
|
return invoke("document_list_databases", { connectionId });
|
||||||
}
|
}
|
||||||
@@ -1533,6 +1551,42 @@ export async function documentFindDocuments(connectionId: string, database: stri
|
|||||||
return invoke("document_find_documents", { connectionId, database, collection, skip, limit, filter, projection, sort, executionId });
|
return invoke("document_find_documents", { connectionId, database, collection, skip, limit, filter, projection, sort, executionId });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function documentListGridFsFiles(connectionId: string, database: string, bucket: string): Promise<MongoGridFsFileInfo[]> {
|
||||||
|
return invoke("document_list_gridfs_files", { connectionId, database, bucket });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentListGridFsBuckets(connectionId: string, database: string): Promise<MongoGridFsBucketInfo[]> {
|
||||||
|
return invoke("document_list_gridfs_buckets", { connectionId, database });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentCreateGridFsBucket(connectionId: string, database: string, bucket: string): Promise<void> {
|
||||||
|
return invoke("document_create_gridfs_bucket", { connectionId, database, bucket });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentDeleteGridFsBucket(connectionId: string, database: string, bucket: string): Promise<void> {
|
||||||
|
return invoke("document_delete_gridfs_bucket", { connectionId, database, bucket });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentDownloadGridFsFile(connectionId: string, database: string, bucket: string, fileId: string): Promise<Uint8Array> {
|
||||||
|
const data = await invoke<number[]>("document_download_gridfs_file", { connectionId, database, bucket, fileId });
|
||||||
|
return new Uint8Array(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentUploadGridFsFile(connectionId: string, database: string, bucket: string, fileName: string, data: Uint8Array, contentType?: string): Promise<string> {
|
||||||
|
return invoke("document_upload_gridfs_file", {
|
||||||
|
connectionId,
|
||||||
|
database,
|
||||||
|
bucket,
|
||||||
|
fileName,
|
||||||
|
data: Array.from(data),
|
||||||
|
contentType,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function documentDeleteGridFsFile(connectionId: string, database: string, bucket: string, fileId: string): Promise<void> {
|
||||||
|
return invoke("document_delete_gridfs_file", { connectionId, database, bucket, fileId });
|
||||||
|
}
|
||||||
|
|
||||||
export async function mongoServerVersion(connectionId: string, database: string, executionId?: string): Promise<string> {
|
export async function mongoServerVersion(connectionId: string, database: string, executionId?: string): Promise<string> {
|
||||||
return invoke("mongo_server_version", { connectionId, database, executionId });
|
return invoke("mongo_server_version", { connectionId, database, executionId });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ export type SidebarSelectionCopyAction = "copy-name" | "none";
|
|||||||
export type SidebarActivation = "single" | "double";
|
export type SidebarActivation = "single" | "double";
|
||||||
|
|
||||||
const dataNodeTypes = new Set<TreeNodeType>(["table", "view", "materialized_view"]);
|
const dataNodeTypes = new Set<TreeNodeType>(["table", "view", "materialized_view"]);
|
||||||
const toggleLeafNodeTypes = new Set<TreeNodeType>(["redis-db", "mq-tenant", "etcd-root", "zookeeper-root", "mongo-collection", "vector-collection", "elasticsearch-index", "user-admin"]);
|
const documentBrowserNodeTypes = new Set<TreeNodeType>(["mongo-collection", "mongo-bucket"]);
|
||||||
|
const toggleLeafNodeTypes = new Set<TreeNodeType>(["redis-db", "mq-tenant", "etcd-root", "zookeeper-root", "mongo-gridfs", "mongo-collection", "mongo-bucket", "vector-collection", "elasticsearch-index", "user-admin"]);
|
||||||
const objectBrowserNodeTypes = new Set<TreeNodeType>(["database", "schema", "object-browser"]);
|
const objectBrowserNodeTypes = new Set<TreeNodeType>(["database", "schema", "object-browser"]);
|
||||||
const sourceNodeTypes = new Set<TreeNodeType>(["materialized_view", "procedure", "function", "sequence", "package", "package-body"]);
|
const sourceNodeTypes = new Set<TreeNodeType>(["materialized_view", "procedure", "function", "sequence", "package", "package-body"]);
|
||||||
const savedSqlNodeTypes = new Set<TreeNodeType>(["saved-sql-file"]);
|
const savedSqlNodeTypes = new Set<TreeNodeType>(["saved-sql-file"]);
|
||||||
@@ -25,6 +26,10 @@ export function objectSourceKindForTreeNode(type: TreeNodeType): ObjectSourceKin
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isDocumentBrowserTreeNode(type: TreeNodeType): boolean {
|
||||||
|
return documentBrowserNodeTypes.has(type);
|
||||||
|
}
|
||||||
|
|
||||||
export function treeNodeRowAction(type: TreeNodeType, canExpand: boolean, activation: SidebarActivation = "single"): TreeNodeRowAction {
|
export function treeNodeRowAction(type: TreeNodeType, canExpand: boolean, activation: SidebarActivation = "single"): TreeNodeRowAction {
|
||||||
if (activation === "double") return "none";
|
if (activation === "double") return "none";
|
||||||
if (dataNodeTypes.has(type)) return "open-data";
|
if (dataNodeTypes.has(type)) return "open-data";
|
||||||
|
|||||||
@@ -1868,18 +1868,32 @@ export const useConnectionStore = defineStore("connection", () => {
|
|||||||
node.isLoading = true;
|
node.isLoading = true;
|
||||||
try {
|
try {
|
||||||
const collections = await api.mongoListCollections(connectionId, database);
|
const collections = await api.mongoListCollections(connectionId, database);
|
||||||
const names = collections.map((c) => c.name);
|
const bucketNames = new Set(collections.filter((c) => c.kind === "bucket" && c.bucketName).map((c) => c.bucketName as string));
|
||||||
setChildren(
|
const hiddenCollectionNames = new Set([...bucketNames].flatMap((bucketName) => [`${bucketName}.files`, `${bucketName}.chunks`]));
|
||||||
node,
|
const collectionNames = collections
|
||||||
sortSidebarNames(names).map((col) => ({
|
.filter((c) => c.kind !== "bucket")
|
||||||
id: `${nodeId}:${col}`,
|
.map((c) => c.name)
|
||||||
label: col,
|
.filter((name) => !hiddenCollectionNames.has(name));
|
||||||
type: "mongo-collection" as const,
|
const collectionChildren = sortSidebarNames(collectionNames).map((col) => ({
|
||||||
|
id: `${nodeId}:${col}`,
|
||||||
|
label: col,
|
||||||
|
type: "mongo-collection" as const,
|
||||||
|
connectionId,
|
||||||
|
database,
|
||||||
|
isExpanded: false,
|
||||||
|
}));
|
||||||
|
const children = [
|
||||||
|
{
|
||||||
|
id: `${nodeId}:__gridfs`,
|
||||||
|
label: i18n.global.t("tree.gridfs"),
|
||||||
|
type: "mongo-gridfs" as const,
|
||||||
connectionId,
|
connectionId,
|
||||||
database,
|
database,
|
||||||
isExpanded: false,
|
isExpanded: false,
|
||||||
})),
|
},
|
||||||
);
|
...collectionChildren,
|
||||||
|
];
|
||||||
|
setChildren(node, children);
|
||||||
node.isExpanded = true;
|
node.isExpanded = true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
recordMetadataLoadError(connectionId, e);
|
recordMetadataLoadError(connectionId, e);
|
||||||
@@ -2649,6 +2663,8 @@ export const useConnectionStore = defineStore("connection", () => {
|
|||||||
await loadMongoCollections(node.connectionId, node.database);
|
await loadMongoCollections(node.connectionId, node.database);
|
||||||
} else if (node.type === "mongo-collection" && node.connectionId && node.database) {
|
} else if (node.type === "mongo-collection" && node.connectionId && node.database) {
|
||||||
await loadTableGroups(node.connectionId, node.database, node.label, node.schema, node.id);
|
await loadTableGroups(node.connectionId, node.database, node.label, node.schema, node.id);
|
||||||
|
} else if (node.type === "mongo-gridfs") {
|
||||||
|
node.isExpanded = true;
|
||||||
} else if (node.type === "database" && node.connectionId && hasTreeNodeDatabaseContext(node)) {
|
} else if (node.type === "database" && node.connectionId && hasTreeNodeDatabaseContext(node)) {
|
||||||
const config = getConfig(node.connectionId);
|
const config = getConfig(node.connectionId);
|
||||||
const effectiveDbType = effectiveDatabaseTypeForConnection(config);
|
const effectiveDbType = effectiveDatabaseTypeForConnection(config);
|
||||||
|
|||||||
@@ -691,6 +691,58 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function openMongoBucket(connectionId: string, database: string, bucketName: string) {
|
||||||
|
const title = `${database}.${bucketName}`;
|
||||||
|
const existing = tabs.value.find((tab) => tab.mode === "mongo-bucket" && tab.connectionId === connectionId && tab.database === database && tab.mongoBucket?.bucketName === bucketName);
|
||||||
|
if (existing) {
|
||||||
|
activeTabId.value = existing.id;
|
||||||
|
return existing.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = uuid();
|
||||||
|
const tab: QueryTab = {
|
||||||
|
id,
|
||||||
|
title,
|
||||||
|
connectionId,
|
||||||
|
database,
|
||||||
|
sql: bucketName,
|
||||||
|
isExecuting: false,
|
||||||
|
isCancelling: false,
|
||||||
|
isExplaining: false,
|
||||||
|
mode: "mongo-bucket",
|
||||||
|
mongoBucket: {
|
||||||
|
bucketName,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
tabs.value.push(tab);
|
||||||
|
activeTabId.value = id;
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
function openMongoGridFs(connectionId: string, database: string) {
|
||||||
|
const existing = tabs.value.find((tab) => tab.mode === "mongo-gridfs" && tab.connectionId === connectionId && tab.database === database);
|
||||||
|
if (existing) {
|
||||||
|
activeTabId.value = existing.id;
|
||||||
|
return existing.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = uuid();
|
||||||
|
const tab: QueryTab = {
|
||||||
|
id,
|
||||||
|
title: "GridFS",
|
||||||
|
connectionId,
|
||||||
|
database,
|
||||||
|
sql: "",
|
||||||
|
isExecuting: false,
|
||||||
|
isCancelling: false,
|
||||||
|
isExplaining: false,
|
||||||
|
mode: "mongo-gridfs",
|
||||||
|
};
|
||||||
|
tabs.value.push(tab);
|
||||||
|
activeTabId.value = id;
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
function openMqAdmin(connectionId: string, target?: { tenant?: string; initialTab?: QueryTab["mqInitialTab"] }) {
|
function openMqAdmin(connectionId: string, target?: { tenant?: string; initialTab?: QueryTab["mqInitialTab"] }) {
|
||||||
const existing = tabs.value.find((tab) => tab.mode === "mq" && tab.connectionId === connectionId);
|
const existing = tabs.value.find((tab) => tab.mode === "mq" && tab.connectionId === connectionId);
|
||||||
if (existing) {
|
if (existing) {
|
||||||
@@ -2778,6 +2830,8 @@ export const useQueryStore = defineStore("query", () => {
|
|||||||
rollbackTransaction,
|
rollbackTransaction,
|
||||||
renameTab,
|
renameTab,
|
||||||
openObjectBrowser,
|
openObjectBrowser,
|
||||||
|
openMongoGridFs,
|
||||||
|
openMongoBucket,
|
||||||
openUserAdmin,
|
openUserAdmin,
|
||||||
openMqAdmin,
|
openMqAdmin,
|
||||||
openNacosAdmin,
|
openNacosAdmin,
|
||||||
|
|||||||
@@ -514,6 +514,9 @@ export type TreeNodeType =
|
|||||||
| "etcd-root"
|
| "etcd-root"
|
||||||
| "zookeeper-root"
|
| "zookeeper-root"
|
||||||
| "mongo-db"
|
| "mongo-db"
|
||||||
|
| "mongo-gridfs"
|
||||||
|
| "mongo-buckets"
|
||||||
|
| "mongo-bucket"
|
||||||
| "mongo-collection"
|
| "mongo-collection"
|
||||||
| "vector-collection"
|
| "vector-collection"
|
||||||
| "elasticsearch-index";
|
| "elasticsearch-index";
|
||||||
@@ -637,7 +640,7 @@ export interface QueryTab {
|
|||||||
executionId?: string;
|
executionId?: string;
|
||||||
isExplaining?: boolean;
|
isExplaining?: boolean;
|
||||||
explainExecutionId?: string;
|
explainExecutionId?: string;
|
||||||
mode: "data" | "query" | "redis" | "redis-dashboard" | "mongo" | "vector" | "etcd" | "zookeeper" | "mq" | "nacos" | "objects" | "structure" | "users";
|
mode: "data" | "query" | "redis" | "redis-dashboard" | "mongo" | "mongo-gridfs" | "mongo-bucket" | "vector" | "etcd" | "zookeeper" | "mq" | "nacos" | "objects" | "structure" | "users";
|
||||||
mqTenant?: string;
|
mqTenant?: string;
|
||||||
mqInitialTab?: "topics";
|
mqInitialTab?: "topics";
|
||||||
nacosNamespace?: string;
|
nacosNamespace?: string;
|
||||||
@@ -684,6 +687,9 @@ export interface QueryTab {
|
|||||||
collection: string;
|
collection: string;
|
||||||
idColumn: "_id";
|
idColumn: "_id";
|
||||||
};
|
};
|
||||||
|
mongoBucket?: {
|
||||||
|
bucketName: string;
|
||||||
|
};
|
||||||
resultEvicted?: boolean;
|
resultEvicted?: boolean;
|
||||||
whereInput?: string;
|
whereInput?: string;
|
||||||
previewSql?: string;
|
previewSql?: string;
|
||||||
@@ -735,4 +741,6 @@ export interface CollectionInfo {
|
|||||||
name: string;
|
name: string;
|
||||||
id: string;
|
id: string;
|
||||||
dimension?: number;
|
dimension?: number;
|
||||||
|
kind?: "collection" | "bucket";
|
||||||
|
bucketName?: string;
|
||||||
}
|
}
|
||||||
@@ -1,13 +1,14 @@
|
|||||||
use mongodb::{
|
use mongodb::{
|
||||||
bson::{doc, oid::ObjectId, Bson, DateTime, Document},
|
bson::{doc, oid::ObjectId, Bson, DateTime, Document},
|
||||||
options::{ClientOptions, IndexOptions},
|
options::{ClientOptions, GridFsBucketOptions, IndexOptions},
|
||||||
Client, IndexModel,
|
Client, Database, IndexModel,
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use super::with_connection_timeout;
|
use super::with_connection_timeout;
|
||||||
|
use crate::document_ops::{MongoGridFsBucketInfo, MongoGridFsFileInfo};
|
||||||
use crate::types::IndexInfo;
|
use crate::types::IndexInfo;
|
||||||
use futures::TryStreamExt;
|
use futures::{io::AsyncReadExt, io::AsyncWriteExt, TryStreamExt};
|
||||||
use percent_encoding::percent_decode_str;
|
use percent_encoding::percent_decode_str;
|
||||||
use std::{collections::HashSet, time::Duration};
|
use std::{collections::HashSet, time::Duration};
|
||||||
|
|
||||||
@@ -143,6 +144,253 @@ pub async fn list_collections(client: &Client, database: &str) -> Result<Vec<Str
|
|||||||
client.database(database).list_collection_names().await.map_err(|e| e.to_string())
|
client.database(database).list_collection_names().await.map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn list_gridfs_files(
|
||||||
|
client: &Client,
|
||||||
|
database: &str,
|
||||||
|
bucket: &str,
|
||||||
|
) -> Result<Vec<MongoGridFsFileInfo>, String> {
|
||||||
|
let bucket = normalized_gridfs_bucket_name(bucket)?;
|
||||||
|
let collection_name = format!("{bucket}.files");
|
||||||
|
let collection = client.database(database).collection::<Document>(&collection_name);
|
||||||
|
let mut cursor =
|
||||||
|
collection.find(doc! {}).sort(doc! { "uploadDate": -1_i32, "_id": -1_i32 }).await.map_err(|e| e.to_string())?;
|
||||||
|
let mut files = Vec::new();
|
||||||
|
while cursor.advance().await.map_err(|e| e.to_string())? {
|
||||||
|
let doc = cursor.deserialize_current().map_err(|e| e.to_string())?;
|
||||||
|
files.push(gridfs_file_info_from_document(&doc));
|
||||||
|
}
|
||||||
|
Ok(files)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn gridfs_bucket_summary(
|
||||||
|
client: &Client,
|
||||||
|
database: &str,
|
||||||
|
bucket: &str,
|
||||||
|
) -> Result<MongoGridFsBucketInfo, String> {
|
||||||
|
let bucket = normalized_gridfs_bucket_name(bucket)?;
|
||||||
|
let collection = client.database(database).collection::<Document>(&format!("{bucket}.files"));
|
||||||
|
let mut cursor = collection
|
||||||
|
.aggregate(vec![doc! {
|
||||||
|
"$group": {
|
||||||
|
"_id": Bson::Null,
|
||||||
|
"fileCount": { "$sum": 1_i32 },
|
||||||
|
"totalBytes": { "$sum": "$length" },
|
||||||
|
}
|
||||||
|
}])
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let mut file_count = 0_u64;
|
||||||
|
let mut total_bytes = 0_i64;
|
||||||
|
if cursor.advance().await.map_err(|e| e.to_string())? {
|
||||||
|
let doc = cursor.deserialize_current().map_err(|e| e.to_string())?;
|
||||||
|
file_count =
|
||||||
|
doc.get_i64("fileCount").or_else(|_| doc.get_i32("fileCount").map(i64::from)).unwrap_or(0).max(0) as u64;
|
||||||
|
total_bytes = doc.get_i64("totalBytes").or_else(|_| doc.get_i32("totalBytes").map(i64::from)).unwrap_or(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(MongoGridFsBucketInfo { name: bucket, file_count, total_bytes })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_gridfs_bucket(client: &Client, database: &str, bucket: &str) -> Result<(), String> {
|
||||||
|
let bucket = normalized_gridfs_bucket_name(bucket)?;
|
||||||
|
let database = client.database(database);
|
||||||
|
let files_name = format!("{bucket}.files");
|
||||||
|
let chunks_name = format!("{bucket}.chunks");
|
||||||
|
let existing: HashSet<String> =
|
||||||
|
database.list_collection_names().await.map_err(|e| e.to_string())?.into_iter().collect();
|
||||||
|
|
||||||
|
if !existing.contains(&files_name) {
|
||||||
|
database.create_collection(&files_name).await.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
if !existing.contains(&chunks_name) {
|
||||||
|
database.create_collection(&chunks_name).await.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
|
||||||
|
database
|
||||||
|
.collection::<Document>(&files_name)
|
||||||
|
.create_index(
|
||||||
|
IndexModel::builder()
|
||||||
|
.keys(doc! { "filename": 1_i32, "uploadDate": 1_i32 })
|
||||||
|
.options(IndexOptions::builder().name(Some("filename_1_uploadDate_1".to_string())).build())
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
database
|
||||||
|
.collection::<Document>(&chunks_name)
|
||||||
|
.create_index(
|
||||||
|
IndexModel::builder()
|
||||||
|
.keys(doc! { "files_id": 1_i32, "n": 1_i32 })
|
||||||
|
.options(IndexOptions::builder().name(Some("files_id_1_n_1".to_string())).unique(Some(true)).build())
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_gridfs_bucket(client: &Client, database: &str, bucket: &str) -> Result<(), String> {
|
||||||
|
let bucket = normalized_gridfs_bucket_name(bucket)?;
|
||||||
|
let database = client.database(database);
|
||||||
|
drop_collection_if_exists(&database, &format!("{bucket}.files")).await?;
|
||||||
|
drop_collection_if_exists(&database, &format!("{bucket}.chunks")).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn download_gridfs_file(
|
||||||
|
client: &Client,
|
||||||
|
database: &str,
|
||||||
|
bucket: &str,
|
||||||
|
file_id: &str,
|
||||||
|
) -> Result<Vec<u8>, String> {
|
||||||
|
let bucket = normalized_gridfs_bucket_name(bucket)?;
|
||||||
|
let trimmed = file_id.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
return Err("GridFS file id is required".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let bson_id = parse_gridfs_file_id(trimmed)?;
|
||||||
|
|
||||||
|
let files_collection = client.database(database).collection::<Document>(&format!("{bucket}.files"));
|
||||||
|
let file_doc = files_collection
|
||||||
|
.find_one(doc! { "_id": bson_id.clone() })
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.ok_or_else(|| "GridFS file not found".to_string())?;
|
||||||
|
let bucket =
|
||||||
|
client.database(database).gridfs_bucket(GridFsBucketOptions::builder().bucket_name(bucket.to_string()).build());
|
||||||
|
let mut stream = bucket
|
||||||
|
.open_download_stream(file_doc.get("_id").cloned().unwrap_or(bson_id))
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
stream.read_to_end(&mut bytes).await.map_err(|e| e.to_string())?;
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn upload_gridfs_file(
|
||||||
|
client: &Client,
|
||||||
|
database: &str,
|
||||||
|
bucket: &str,
|
||||||
|
file_name: &str,
|
||||||
|
data: &[u8],
|
||||||
|
content_type: Option<&str>,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let bucket = normalized_gridfs_bucket_name(bucket)?;
|
||||||
|
let file_name = file_name.trim();
|
||||||
|
if file_name.is_empty() {
|
||||||
|
return Err("GridFS file name is required".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
create_gridfs_bucket(client, database, &bucket).await?;
|
||||||
|
|
||||||
|
let database_ref = client.database(database);
|
||||||
|
let gridfs_bucket = database_ref.gridfs_bucket(GridFsBucketOptions::builder().bucket_name(bucket.clone()).build());
|
||||||
|
let mut upload_action = gridfs_bucket.open_upload_stream(file_name);
|
||||||
|
if let Some(content_type) = content_type.map(str::trim).filter(|value| !value.is_empty()) {
|
||||||
|
upload_action = upload_action.metadata(doc! { "contentType": content_type });
|
||||||
|
}
|
||||||
|
let mut stream = upload_action.await.map_err(|e| e.to_string())?;
|
||||||
|
let file_id = stream.id().clone();
|
||||||
|
stream.write_all(data).await.map_err(|e| e.to_string())?;
|
||||||
|
stream.close().await.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
if let Some(content_type) = content_type.map(str::trim).filter(|value| !value.is_empty()) {
|
||||||
|
database_ref
|
||||||
|
.collection::<Document>(&format!("{bucket}.files"))
|
||||||
|
.update_one(doc! { "_id": file_id.clone() }, doc! { "$set": { "contentType": content_type } })
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(gridfs_file_id_to_string(&file_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_gridfs_file(client: &Client, database: &str, bucket: &str, file_id: &str) -> Result<(), String> {
|
||||||
|
let bucket = normalized_gridfs_bucket_name(bucket)?;
|
||||||
|
let bson_id = parse_gridfs_file_id(file_id.trim())?;
|
||||||
|
client
|
||||||
|
.database(database)
|
||||||
|
.gridfs_bucket(GridFsBucketOptions::builder().bucket_name(bucket).build())
|
||||||
|
.delete(bson_id)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gridfs_file_id_to_string(id: &Bson) -> String {
|
||||||
|
match id {
|
||||||
|
Bson::ObjectId(value) => value.to_hex(),
|
||||||
|
Bson::String(value) => value.clone(),
|
||||||
|
_ => id.clone().into_relaxed_extjson().to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gridfs_upload_date_to_string(value: &DateTime) -> String {
|
||||||
|
value.try_to_rfc3339_string().unwrap_or_else(|_| value.timestamp_millis().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gridfs_file_info_from_document(doc: &Document) -> MongoGridFsFileInfo {
|
||||||
|
let id = gridfs_file_id_to_string(doc.get("_id").unwrap_or(&Bson::Null));
|
||||||
|
let filename = doc.get_str("filename").ok().map(str::to_string);
|
||||||
|
let length = doc.get_i64("length").or_else(|_| doc.get_i32("length").map(i64::from)).unwrap_or(0);
|
||||||
|
let chunk_size =
|
||||||
|
doc.get_i32("chunkSize").or_else(|_| doc.get_i64("chunkSize").map(|value| value as i32)).unwrap_or(0);
|
||||||
|
let upload_date = doc.get_datetime("uploadDate").ok().map(gridfs_upload_date_to_string);
|
||||||
|
let metadata = doc.get_document("metadata").ok().map(|value| Bson::Document(value.clone()).into_relaxed_extjson());
|
||||||
|
let md5 = doc.get_str("md5").ok().map(str::to_string);
|
||||||
|
let content_type = doc.get_str("contentType").ok().map(str::to_string).or_else(|| {
|
||||||
|
doc.get_document("metadata").ok().and_then(|meta| meta.get_str("contentType").ok().map(str::to_string))
|
||||||
|
});
|
||||||
|
let aliases = doc.get_array("aliases").ok().and_then(|values| {
|
||||||
|
let aliases: Vec<String> = values.iter().filter_map(|value| value.as_str().map(str::to_string)).collect();
|
||||||
|
if aliases.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(aliases)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
MongoGridFsFileInfo { id, filename, length, chunk_size, upload_date, metadata, md5, content_type, aliases }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_gridfs_file_id(file_id: &str) -> Result<Bson, String> {
|
||||||
|
if let Ok(value) = serde_json::from_str::<serde_json::Value>(file_id) {
|
||||||
|
return Bson::try_from(value).map_err(|e| format!("Invalid GridFS file id: {e}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Ok(object_id) = ObjectId::parse_str(file_id) {
|
||||||
|
return Ok(Bson::ObjectId(object_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Bson::String(file_id.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalized_gridfs_bucket_name(bucket: &str) -> Result<String, String> {
|
||||||
|
let bucket = bucket.trim();
|
||||||
|
if bucket.is_empty() {
|
||||||
|
return Err("GridFS bucket name is required".to_string());
|
||||||
|
}
|
||||||
|
if bucket.ends_with(".files") || bucket.ends_with(".chunks") {
|
||||||
|
return Err("Use the GridFS bucket name without the .files or .chunks suffix".to_string());
|
||||||
|
}
|
||||||
|
Ok(bucket.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn drop_collection_if_exists(database: &Database, collection_name: &str) -> Result<(), String> {
|
||||||
|
match database.collection::<Document>(collection_name).drop().await {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
Err(error) if mongo_namespace_missing(&error.to_string()) => Ok(()),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mongo_namespace_missing(error: &str) -> bool {
|
||||||
|
let lower = error.to_lowercase();
|
||||||
|
lower.contains("ns not found") || lower.contains("namespace not found")
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn create_database(client: &Client, database: &str) -> Result<(), String> {
|
pub async fn create_database(client: &Client, database: &str) -> Result<(), String> {
|
||||||
let database = database.trim();
|
let database = database.trim();
|
||||||
if database.is_empty() {
|
if database.is_empty() {
|
||||||
@@ -1236,6 +1484,46 @@ mod tests {
|
|||||||
assert!(matches!(doc.get("count"), Some(Bson::Int64(42))));
|
assert!(matches!(doc.get("count"), Some(Bson::Int64(42))));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_gridfs_file_id_accepts_extended_json_object_id() {
|
||||||
|
let id = parse_gridfs_file_id(r#"{"$oid":"507f1f77bcf86cd799439011"}"#).unwrap();
|
||||||
|
|
||||||
|
assert!(matches!(id, Bson::ObjectId(oid) if oid.to_hex() == "507f1f77bcf86cd799439011"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_gridfs_file_id_accepts_json_string_ids() {
|
||||||
|
let id = parse_gridfs_file_id(r#""report-42""#).unwrap();
|
||||||
|
|
||||||
|
assert!(matches!(id, Bson::String(value) if value == "report-42"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gridfs_file_id_to_string_keeps_plain_strings_unquoted() {
|
||||||
|
let id = gridfs_file_id_to_string(&Bson::String("report-42".to_string()));
|
||||||
|
|
||||||
|
assert_eq!(id, "report-42");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gridfs_file_info_includes_navicat_style_metadata_fields() {
|
||||||
|
let info = gridfs_file_info_from_document(&doc! {
|
||||||
|
"_id": "report-42",
|
||||||
|
"filename": "report.zip",
|
||||||
|
"length": 128_i64,
|
||||||
|
"chunkSize": 255_i32,
|
||||||
|
"md5": "abc123",
|
||||||
|
"contentType": "application/zip",
|
||||||
|
"aliases": ["archive", "nightly"],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert_eq!(info.id, "report-42");
|
||||||
|
assert_eq!(info.filename.as_deref(), Some("report.zip"));
|
||||||
|
assert_eq!(info.md5.as_deref(), Some("abc123"));
|
||||||
|
assert_eq!(info.content_type.as_deref(), Some("application/zip"));
|
||||||
|
assert_eq!(info.aliases, Some(vec!["archive".to_string(), "nightly".to_string()]));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn json_object_to_document_parses_find_projection() {
|
fn json_object_to_document_parses_find_projection() {
|
||||||
let value = serde_json::json!({
|
let value = serde_json::json!({
|
||||||
|
|||||||
@@ -28,10 +28,13 @@ const PATH_SEGMENT_ENCODE_SET: &AsciiSet = &CONTROLS
|
|||||||
const QUERY_VALUE_ENCODE_SET: &AsciiSet = &PATH_SEGMENT_ENCODE_SET.add(b'&').add(b'=').add(b'+');
|
const QUERY_VALUE_ENCODE_SET: &AsciiSet = &PATH_SEGMENT_ENCODE_SET.add(b'&').add(b'=').add(b'+');
|
||||||
|
|
||||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct CollectionInfo {
|
pub struct CollectionInfo {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub dimension: Option<u32>,
|
pub dimension: Option<u32>,
|
||||||
|
pub kind: Option<String>,
|
||||||
|
pub bucket_name: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -177,7 +180,13 @@ async fn list_qdrant_collections(client: &VectorClient) -> Result<Vec<Collection
|
|||||||
.flatten()
|
.flatten()
|
||||||
.filter_map(|item| {
|
.filter_map(|item| {
|
||||||
let name = item.get("name").and_then(Value::as_str)?;
|
let name = item.get("name").and_then(Value::as_str)?;
|
||||||
Some(CollectionInfo { name: name.to_string(), id: name.to_string(), dimension: None })
|
Some(CollectionInfo {
|
||||||
|
name: name.to_string(),
|
||||||
|
id: name.to_string(),
|
||||||
|
dimension: None,
|
||||||
|
kind: None,
|
||||||
|
bucket_name: None,
|
||||||
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
infos.sort_by(|a, b| a.name.cmp(&b.name));
|
infos.sort_by(|a, b| a.name.cmp(&b.name));
|
||||||
@@ -196,7 +205,7 @@ async fn list_milvus_collections(client: &VectorClient, database: &str) -> Resul
|
|||||||
.iter()
|
.iter()
|
||||||
.filter_map(|item| {
|
.filter_map(|item| {
|
||||||
let name = collection_name_from_milvus_item(item)?;
|
let name = collection_name_from_milvus_item(item)?;
|
||||||
Some(CollectionInfo { name: name.clone(), id: name, dimension: None })
|
Some(CollectionInfo { name: name.clone(), id: name, dimension: None, kind: None, bucket_name: None })
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
_ => Vec::new(),
|
_ => Vec::new(),
|
||||||
@@ -216,7 +225,7 @@ async fn list_weaviate_collections(client: &VectorClient) -> Result<Vec<Collecti
|
|||||||
let body = send_json(client.get("/v1/schema"), "Weaviate").await?;
|
let body = send_json(client.get("/v1/schema"), "Weaviate").await?;
|
||||||
let mut infos: Vec<CollectionInfo> = weaviate_collection_names_from_schema(&body)
|
let mut infos: Vec<CollectionInfo> = weaviate_collection_names_from_schema(&body)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|name| CollectionInfo { name: name.clone(), id: name, dimension: None })
|
.map(|name| CollectionInfo { name: name.clone(), id: name, dimension: None, kind: None, bucket_name: None })
|
||||||
.collect();
|
.collect();
|
||||||
infos.sort_by(|a, b| a.name.cmp(&b.name));
|
infos.sort_by(|a, b| a.name.cmp(&b.name));
|
||||||
Ok(infos)
|
Ok(infos)
|
||||||
@@ -234,7 +243,13 @@ async fn list_chroma_collections(client: &VectorClient) -> Result<Vec<Collection
|
|||||||
let name = item.get("name").and_then(Value::as_str)?;
|
let name = item.get("name").and_then(Value::as_str)?;
|
||||||
let id = item.get("id").and_then(Value::as_str)?;
|
let id = item.get("id").and_then(Value::as_str)?;
|
||||||
let dimension = item.get("dimension").and_then(|v| v.as_u64()).map(|d| d as u32);
|
let dimension = item.get("dimension").and_then(|v| v.as_u64()).map(|d| d as u32);
|
||||||
Some(CollectionInfo { name: name.to_string(), id: id.to_string(), dimension })
|
Some(CollectionInfo {
|
||||||
|
name: name.to_string(),
|
||||||
|
id: id.to_string(),
|
||||||
|
dimension,
|
||||||
|
kind: None,
|
||||||
|
bucket_name: None,
|
||||||
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
infos.sort_by(|a, b| a.name.cmp(&b.name));
|
infos.sort_by(|a, b| a.name.cmp(&b.name));
|
||||||
@@ -251,7 +266,13 @@ pub async fn get_collection_detail(
|
|||||||
VectorDbKind::Milvus => get_milvus_collection_detail(client, database, collection).await,
|
VectorDbKind::Milvus => get_milvus_collection_detail(client, database, collection).await,
|
||||||
VectorDbKind::Weaviate => {
|
VectorDbKind::Weaviate => {
|
||||||
// Weaviate REST API does not expose vector dimension
|
// Weaviate REST API does not expose vector dimension
|
||||||
Ok(CollectionInfo { name: collection.to_string(), id: collection.to_string(), dimension: None })
|
Ok(CollectionInfo {
|
||||||
|
name: collection.to_string(),
|
||||||
|
id: collection.to_string(),
|
||||||
|
dimension: None,
|
||||||
|
kind: None,
|
||||||
|
bucket_name: None,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
VectorDbKind::ChromaDb => get_chroma_collection_detail(client, collection).await,
|
VectorDbKind::ChromaDb => get_chroma_collection_detail(client, collection).await,
|
||||||
}
|
}
|
||||||
@@ -268,7 +289,13 @@ async fn get_qdrant_collection_detail(client: &VectorClient, collection: &str) -
|
|||||||
.and_then(|obj| obj.values().find_map(|v| v.get("size").and_then(|s| s.as_u64())))
|
.and_then(|obj| obj.values().find_map(|v| v.get("size").and_then(|s| s.as_u64())))
|
||||||
})
|
})
|
||||||
.map(|d| d as u32);
|
.map(|d| d as u32);
|
||||||
Ok(CollectionInfo { name: collection.to_string(), id: collection.to_string(), dimension: dim })
|
Ok(CollectionInfo {
|
||||||
|
name: collection.to_string(),
|
||||||
|
id: collection.to_string(),
|
||||||
|
dimension: dim,
|
||||||
|
kind: None,
|
||||||
|
bucket_name: None,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn milvus_vector_dim_from_field(field: &Value) -> Option<u32> {
|
fn milvus_vector_dim_from_field(field: &Value) -> Option<u32> {
|
||||||
@@ -319,7 +346,13 @@ async fn get_milvus_collection_detail(
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
.and_then(milvus_vector_dim_from_field);
|
.and_then(milvus_vector_dim_from_field);
|
||||||
Ok(CollectionInfo { name: collection.to_string(), id: collection.to_string(), dimension: dim })
|
Ok(CollectionInfo {
|
||||||
|
name: collection.to_string(),
|
||||||
|
id: collection.to_string(),
|
||||||
|
dimension: dim,
|
||||||
|
kind: None,
|
||||||
|
bucket_name: None,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_chroma_collection_detail(client: &VectorClient, collection: &str) -> Result<CollectionInfo, String> {
|
async fn get_chroma_collection_detail(client: &VectorClient, collection: &str) -> Result<CollectionInfo, String> {
|
||||||
@@ -334,7 +367,7 @@ async fn get_chroma_collection_detail(client: &VectorClient, collection: &str) -
|
|||||||
let name = body.get("name").and_then(Value::as_str).unwrap_or(collection);
|
let name = body.get("name").and_then(Value::as_str).unwrap_or(collection);
|
||||||
let id = body.get("id").and_then(Value::as_str).unwrap_or(collection);
|
let id = body.get("id").and_then(Value::as_str).unwrap_or(collection);
|
||||||
let dimension = body.get("dimension").and_then(|v| v.as_u64()).map(|d| d as u32);
|
let dimension = body.get("dimension").and_then(|v| v.as_u64()).map(|d| d as u32);
|
||||||
Ok(CollectionInfo { name: name.to_string(), id: id.to_string(), dimension })
|
Ok(CollectionInfo { name: name.to_string(), id: id.to_string(), dimension, kind: None, bucket_name: None })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn chroma_get_response_to_rows(body: &Value) -> Vec<Value> {
|
fn chroma_get_response_to_rows(body: &Value) -> Vec<Value> {
|
||||||
@@ -773,7 +806,13 @@ mod tests {
|
|||||||
.filter_map(|item| {
|
.filter_map(|item| {
|
||||||
let name = item.get("name").and_then(|v| v.as_str())?;
|
let name = item.get("name").and_then(|v| v.as_str())?;
|
||||||
let id = item.get("id").and_then(|v| v.as_str())?;
|
let id = item.get("id").and_then(|v| v.as_str())?;
|
||||||
Some(CollectionInfo { name: name.to_string(), id: id.to_string(), dimension: None })
|
Some(CollectionInfo {
|
||||||
|
name: name.to_string(),
|
||||||
|
id: id.to_string(),
|
||||||
|
dimension: None,
|
||||||
|
kind: None,
|
||||||
|
bucket_name: None,
|
||||||
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
assert_eq!(infos.len(), 2);
|
assert_eq!(infos.len(), 2);
|
||||||
|
|||||||
@@ -5,6 +5,28 @@ use crate::db::{elasticsearch_driver, mongo_driver, vector_driver};
|
|||||||
|
|
||||||
pub use crate::db::vector_driver::CollectionInfo;
|
pub use crate::db::vector_driver::CollectionInfo;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct MongoGridFsFileInfo {
|
||||||
|
pub id: String,
|
||||||
|
pub filename: Option<String>,
|
||||||
|
pub length: i64,
|
||||||
|
pub chunk_size: i32,
|
||||||
|
pub upload_date: Option<String>,
|
||||||
|
pub metadata: Option<serde_json::Value>,
|
||||||
|
pub md5: Option<String>,
|
||||||
|
pub content_type: Option<String>,
|
||||||
|
pub aliases: Option<Vec<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct MongoGridFsBucketInfo {
|
||||||
|
pub name: String,
|
||||||
|
pub file_count: u64,
|
||||||
|
pub total_bytes: i64,
|
||||||
|
}
|
||||||
|
|
||||||
fn sort_names(mut names: Vec<String>) -> Vec<String> {
|
fn sort_names(mut names: Vec<String>) -> Vec<String> {
|
||||||
names.sort_by(|left, right| {
|
names.sort_by(|left, right| {
|
||||||
let left_lower = left.to_lowercase();
|
let left_lower = left.to_lowercase();
|
||||||
@@ -61,6 +83,45 @@ fn mongo_list_databases_unauthorized(error: &str) -> bool {
|
|||||||
lower.contains("not authorized") && lower.contains("listdatabases")
|
lower.contains("not authorized") && lower.contains("listdatabases")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn mongo_collection_info(name: String) -> CollectionInfo {
|
||||||
|
CollectionInfo {
|
||||||
|
name: name.clone(),
|
||||||
|
id: name,
|
||||||
|
dimension: None,
|
||||||
|
kind: Some("collection".to_string()),
|
||||||
|
bucket_name: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn mongo_gridfs_bucket_names(names: &[String]) -> Vec<String> {
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
let name_set: BTreeSet<&str> = names.iter().map(String::as_str).collect();
|
||||||
|
let bucket_names: Vec<String> = names
|
||||||
|
.iter()
|
||||||
|
.filter_map(|name| name.strip_suffix(".files"))
|
||||||
|
.filter(|prefix| name_set.contains(format!("{prefix}.chunks").as_str()))
|
||||||
|
.map(str::to_string)
|
||||||
|
.collect::<BTreeSet<_>>()
|
||||||
|
.into_iter()
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
sort_names(bucket_names)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mongo_bucket_infos(names: &[String]) -> Vec<CollectionInfo> {
|
||||||
|
mongo_gridfs_bucket_names(names)
|
||||||
|
.into_iter()
|
||||||
|
.map(|bucket_name| CollectionInfo {
|
||||||
|
name: bucket_name.clone(),
|
||||||
|
id: format!("bucket:{bucket_name}"),
|
||||||
|
dimension: None,
|
||||||
|
kind: Some("bucket".to_string()),
|
||||||
|
bucket_name: Some(bucket_name),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn list_collections_core(
|
pub async fn list_collections_core(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
connection_id: &str,
|
connection_id: &str,
|
||||||
@@ -71,22 +132,148 @@ pub async fn list_collections_core(
|
|||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::MongoDb(client) => {
|
PoolKind::MongoDb(client) => {
|
||||||
let names = sort_names(mongo_driver::list_collections(client, database).await?);
|
let names = sort_names(mongo_driver::list_collections(client, database).await?);
|
||||||
Ok(names.into_iter().map(|n| CollectionInfo { name: n.clone(), id: n, dimension: None }).collect())
|
let mut infos = mongo_bucket_infos(&names);
|
||||||
|
infos.extend(names.into_iter().map(mongo_collection_info));
|
||||||
|
Ok(infos)
|
||||||
}
|
}
|
||||||
PoolKind::Elasticsearch(client) => {
|
PoolKind::Elasticsearch(client) => {
|
||||||
let names = sort_names(elasticsearch_driver::list_indices(client).await?);
|
let names = sort_names(elasticsearch_driver::list_indices(client).await?);
|
||||||
Ok(names.into_iter().map(|n| CollectionInfo { name: n.clone(), id: n, dimension: None }).collect())
|
Ok(names
|
||||||
|
.into_iter()
|
||||||
|
.map(|n| CollectionInfo { name: n.clone(), id: n, dimension: None, kind: None, bucket_name: None })
|
||||||
|
.collect())
|
||||||
}
|
}
|
||||||
PoolKind::VectorDb(client) => vector_driver::list_collections_with_db(&client, database).await,
|
PoolKind::VectorDb(client) => vector_driver::list_collections_with_db(&client, database).await,
|
||||||
PoolKind::Agent(client) => {
|
PoolKind::Agent(client) => {
|
||||||
let mut client = client.lock().await;
|
let mut client = client.lock().await;
|
||||||
let names = sort_names(client.mongo_list_collections(database).await?);
|
let names = sort_names(client.mongo_list_collections(database).await?);
|
||||||
Ok(names.into_iter().map(|n| CollectionInfo { name: n.clone(), id: n, dimension: None }).collect())
|
let mut infos = mongo_bucket_infos(&names);
|
||||||
|
infos.extend(names.into_iter().map(mongo_collection_info));
|
||||||
|
Ok(infos)
|
||||||
}
|
}
|
||||||
_ => Err("Not a MongoDB/Elasticsearch/vector connection".to_string()),
|
_ => Err("Not a MongoDB/Elasticsearch/vector connection".to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn list_gridfs_files_core(
|
||||||
|
state: &AppState,
|
||||||
|
connection_id: &str,
|
||||||
|
database: &str,
|
||||||
|
bucket: &str,
|
||||||
|
) -> Result<Vec<MongoGridFsFileInfo>, String> {
|
||||||
|
ensure_document_pool(state, connection_id).await?;
|
||||||
|
let connections = state.connections.read().await;
|
||||||
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
|
PoolKind::MongoDb(client) => mongo_driver::list_gridfs_files(client, database, bucket).await,
|
||||||
|
PoolKind::Agent(_) => Err("MongoDB legacy agent does not support GridFS file browsing".to_string()),
|
||||||
|
_ => Err("Not a MongoDB connection".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_gridfs_buckets_core(
|
||||||
|
state: &AppState,
|
||||||
|
connection_id: &str,
|
||||||
|
database: &str,
|
||||||
|
) -> Result<Vec<MongoGridFsBucketInfo>, String> {
|
||||||
|
ensure_document_pool(state, connection_id).await?;
|
||||||
|
let connections = state.connections.read().await;
|
||||||
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
|
PoolKind::MongoDb(client) => {
|
||||||
|
let names = sort_names(mongo_driver::list_collections(client, database).await?);
|
||||||
|
let bucket_names = mongo_gridfs_bucket_names(&names);
|
||||||
|
let mut buckets = Vec::with_capacity(bucket_names.len());
|
||||||
|
for bucket_name in bucket_names {
|
||||||
|
buckets.push(mongo_driver::gridfs_bucket_summary(client, database, &bucket_name).await?);
|
||||||
|
}
|
||||||
|
Ok(buckets)
|
||||||
|
}
|
||||||
|
PoolKind::Agent(_) => Err("MongoDB legacy agent does not support GridFS bucket browsing".to_string()),
|
||||||
|
_ => Err("Not a MongoDB connection".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_gridfs_bucket_core(
|
||||||
|
state: &AppState,
|
||||||
|
connection_id: &str,
|
||||||
|
database: &str,
|
||||||
|
bucket: &str,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
ensure_document_pool(state, connection_id).await?;
|
||||||
|
let connections = state.connections.read().await;
|
||||||
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
|
PoolKind::MongoDb(client) => mongo_driver::create_gridfs_bucket(client, database, bucket).await,
|
||||||
|
PoolKind::Agent(_) => Err("MongoDB legacy agent does not support GridFS bucket creation".to_string()),
|
||||||
|
_ => Err("Not a MongoDB connection".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_gridfs_bucket_core(
|
||||||
|
state: &AppState,
|
||||||
|
connection_id: &str,
|
||||||
|
database: &str,
|
||||||
|
bucket: &str,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
ensure_document_pool(state, connection_id).await?;
|
||||||
|
let connections = state.connections.read().await;
|
||||||
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
|
PoolKind::MongoDb(client) => mongo_driver::delete_gridfs_bucket(client, database, bucket).await,
|
||||||
|
PoolKind::Agent(_) => Err("MongoDB legacy agent does not support GridFS bucket deletion".to_string()),
|
||||||
|
_ => Err("Not a MongoDB connection".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn download_gridfs_file_core(
|
||||||
|
state: &AppState,
|
||||||
|
connection_id: &str,
|
||||||
|
database: &str,
|
||||||
|
bucket: &str,
|
||||||
|
file_id: &str,
|
||||||
|
) -> Result<Vec<u8>, String> {
|
||||||
|
ensure_document_pool(state, connection_id).await?;
|
||||||
|
let connections = state.connections.read().await;
|
||||||
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
|
PoolKind::MongoDb(client) => mongo_driver::download_gridfs_file(client, database, bucket, file_id).await,
|
||||||
|
PoolKind::Agent(_) => Err("MongoDB legacy agent does not support GridFS download".to_string()),
|
||||||
|
_ => Err("Not a MongoDB connection".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn upload_gridfs_file_core(
|
||||||
|
state: &AppState,
|
||||||
|
connection_id: &str,
|
||||||
|
database: &str,
|
||||||
|
bucket: &str,
|
||||||
|
file_name: &str,
|
||||||
|
data: &[u8],
|
||||||
|
content_type: Option<&str>,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
ensure_document_pool(state, connection_id).await?;
|
||||||
|
let connections = state.connections.read().await;
|
||||||
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
|
PoolKind::MongoDb(client) => {
|
||||||
|
mongo_driver::upload_gridfs_file(client, database, bucket, file_name, data, content_type).await
|
||||||
|
}
|
||||||
|
PoolKind::Agent(_) => Err("MongoDB legacy agent does not support GridFS uploads".to_string()),
|
||||||
|
_ => Err("Not a MongoDB connection".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_gridfs_file_core(
|
||||||
|
state: &AppState,
|
||||||
|
connection_id: &str,
|
||||||
|
database: &str,
|
||||||
|
bucket: &str,
|
||||||
|
file_id: &str,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
ensure_document_pool(state, connection_id).await?;
|
||||||
|
let connections = state.connections.read().await;
|
||||||
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
|
PoolKind::MongoDb(client) => mongo_driver::delete_gridfs_file(client, database, bucket, file_id).await,
|
||||||
|
PoolKind::Agent(_) => Err("MongoDB legacy agent does not support GridFS file deletion".to_string()),
|
||||||
|
_ => Err("Not a MongoDB connection".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub async fn find_documents_core(
|
pub async fn find_documents_core(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
@@ -233,7 +420,7 @@ pub async fn delete_document_core(
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{fallback_mongo_database, mongo_list_databases_unauthorized, sort_names};
|
use super::{fallback_mongo_database, mongo_gridfs_bucket_names, mongo_list_databases_unauthorized, sort_names};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn sorts_names_case_insensitively() {
|
fn sorts_names_case_insensitively() {
|
||||||
@@ -263,4 +450,18 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert_eq!(fallback_mongo_database("not authorized", None).unwrap_err(), "not authorized");
|
assert_eq!(fallback_mongo_database("not authorized", None).unwrap_err(), "not authorized");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn extracts_gridfs_bucket_names_from_matching_files_and_chunks_collections() {
|
||||||
|
let buckets = mongo_gridfs_bucket_names(&[
|
||||||
|
"orders.files".to_string(),
|
||||||
|
"orders.chunks".to_string(),
|
||||||
|
"reports.files".to_string(),
|
||||||
|
"reports.chunks".to_string(),
|
||||||
|
"reports.files".to_string(),
|
||||||
|
"loose.files".to_string(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert_eq!(buckets, vec!["orders".to_string(), "reports".to_string()]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -449,6 +449,13 @@ async fn main() {
|
|||||||
.route("/document-store/list-databases", post(routes::document_store::list_databases))
|
.route("/document-store/list-databases", post(routes::document_store::list_databases))
|
||||||
.route("/document-store/list-collections", post(routes::document_store::list_collections))
|
.route("/document-store/list-collections", post(routes::document_store::list_collections))
|
||||||
.route("/document-store/find-documents", post(routes::document_store::find_documents))
|
.route("/document-store/find-documents", post(routes::document_store::find_documents))
|
||||||
|
.route("/document-store/list-gridfs-buckets", post(routes::document_store::list_gridfs_buckets))
|
||||||
|
.route("/document-store/create-gridfs-bucket", post(routes::document_store::create_gridfs_bucket))
|
||||||
|
.route("/document-store/delete-gridfs-bucket", post(routes::document_store::delete_gridfs_bucket))
|
||||||
|
.route("/document-store/list-gridfs-files", post(routes::document_store::list_gridfs_files))
|
||||||
|
.route("/document-store/download-gridfs-file", post(routes::document_store::download_gridfs_file))
|
||||||
|
.route("/document-store/upload-gridfs-file", post(routes::document_store::upload_gridfs_file))
|
||||||
|
.route("/document-store/delete-gridfs-file", post(routes::document_store::delete_gridfs_file))
|
||||||
.route("/document-store/insert-document", post(routes::document_store::insert_document))
|
.route("/document-store/insert-document", post(routes::document_store::insert_document))
|
||||||
.route("/document-store/update-document", post(routes::document_store::update_document))
|
.route("/document-store/update-document", post(routes::document_store::update_document))
|
||||||
.route("/document-store/delete-document", post(routes::document_store::delete_document))
|
.route("/document-store/delete-document", post(routes::document_store::delete_document))
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use axum::extract::State;
|
use axum::extract::{Multipart, State};
|
||||||
use axum::Json;
|
use axum::Json;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
@@ -99,6 +99,32 @@ pub struct DocumentDeleteRequest {
|
|||||||
pub routing: Option<String>,
|
pub routing: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct GridFsBucketRequest {
|
||||||
|
pub connection_id: String,
|
||||||
|
pub database: String,
|
||||||
|
pub bucket: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct GridFsDownloadRequest {
|
||||||
|
pub connection_id: String,
|
||||||
|
pub database: String,
|
||||||
|
pub bucket: String,
|
||||||
|
pub file_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct GridFsFileDeleteRequest {
|
||||||
|
pub connection_id: String,
|
||||||
|
pub database: String,
|
||||||
|
pub bucket: String,
|
||||||
|
pub file_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn list_databases(
|
pub async fn list_databases(
|
||||||
State(state): State<Arc<WebState>>,
|
State(state): State<Arc<WebState>>,
|
||||||
Json(req): Json<DocumentListDatabasesRequest>,
|
Json(req): Json<DocumentListDatabasesRequest>,
|
||||||
@@ -193,3 +219,134 @@ pub async fn delete_document(
|
|||||||
.map_err(AppError)?;
|
.map_err(AppError)?;
|
||||||
Ok(Json(result))
|
Ok(Json(result))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn list_gridfs_files(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Json(req): Json<GridFsBucketRequest>,
|
||||||
|
) -> Result<Json<Vec<dbx_core::document_ops::MongoGridFsFileInfo>>, AppError> {
|
||||||
|
let result =
|
||||||
|
dbx_core::document_ops::list_gridfs_files_core(&state.app, &req.connection_id, &req.database, &req.bucket)
|
||||||
|
.await
|
||||||
|
.map_err(AppError)?;
|
||||||
|
Ok(Json(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_gridfs_buckets(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Json(req): Json<DocumentListCollectionsRequest>,
|
||||||
|
) -> Result<Json<Vec<dbx_core::document_ops::MongoGridFsBucketInfo>>, AppError> {
|
||||||
|
let result = dbx_core::document_ops::list_gridfs_buckets_core(&state.app, &req.connection_id, &req.database)
|
||||||
|
.await
|
||||||
|
.map_err(AppError)?;
|
||||||
|
Ok(Json(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_gridfs_bucket(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Json(req): Json<GridFsBucketRequest>,
|
||||||
|
) -> Result<Json<()>, AppError> {
|
||||||
|
ensure_writable(&state.app, &req.connection_id, "Create GridFS bucket").await?;
|
||||||
|
dbx_core::document_ops::create_gridfs_bucket_core(&state.app, &req.connection_id, &req.database, &req.bucket)
|
||||||
|
.await
|
||||||
|
.map_err(AppError)?;
|
||||||
|
Ok(Json(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_gridfs_bucket(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Json(req): Json<GridFsBucketRequest>,
|
||||||
|
) -> Result<Json<()>, AppError> {
|
||||||
|
ensure_writable(&state.app, &req.connection_id, "Delete GridFS bucket").await?;
|
||||||
|
dbx_core::document_ops::delete_gridfs_bucket_core(&state.app, &req.connection_id, &req.database, &req.bucket)
|
||||||
|
.await
|
||||||
|
.map_err(AppError)?;
|
||||||
|
Ok(Json(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn download_gridfs_file(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Json(req): Json<GridFsDownloadRequest>,
|
||||||
|
) -> Result<Json<Vec<u8>>, AppError> {
|
||||||
|
let result = dbx_core::document_ops::download_gridfs_file_core(
|
||||||
|
&state.app,
|
||||||
|
&req.connection_id,
|
||||||
|
&req.database,
|
||||||
|
&req.bucket,
|
||||||
|
&req.file_id,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(AppError)?;
|
||||||
|
Ok(Json(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn upload_gridfs_file(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
mut multipart: Multipart,
|
||||||
|
) -> Result<Json<String>, AppError> {
|
||||||
|
let mut connection_id: Option<String> = None;
|
||||||
|
let mut database: Option<String> = None;
|
||||||
|
let mut bucket: Option<String> = None;
|
||||||
|
let mut file_name: Option<String> = None;
|
||||||
|
let mut content_type: Option<String> = None;
|
||||||
|
let mut file_bytes: Option<Vec<u8>> = None;
|
||||||
|
|
||||||
|
while let Some(field) = multipart.next_field().await.map_err(|e| AppError(e.to_string()))? {
|
||||||
|
let name = field.name().unwrap_or_default().to_string();
|
||||||
|
match name.as_str() {
|
||||||
|
"connectionId" => connection_id = Some(field.text().await.map_err(|e| AppError(e.to_string()))?),
|
||||||
|
"database" => database = Some(field.text().await.map_err(|e| AppError(e.to_string()))?),
|
||||||
|
"bucket" => bucket = Some(field.text().await.map_err(|e| AppError(e.to_string()))?),
|
||||||
|
"fileName" => file_name = Some(field.text().await.map_err(|e| AppError(e.to_string()))?),
|
||||||
|
"contentType" => content_type = Some(field.text().await.map_err(|e| AppError(e.to_string()))?),
|
||||||
|
"file" => {
|
||||||
|
if file_name.is_none() {
|
||||||
|
file_name = field.file_name().map(str::to_string);
|
||||||
|
}
|
||||||
|
if content_type.is_none() {
|
||||||
|
content_type = field.content_type().map(str::to_string);
|
||||||
|
}
|
||||||
|
file_bytes = Some(field.bytes().await.map_err(|e| AppError(e.to_string()))?.to_vec());
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let _ = field.bytes().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let connection_id = connection_id.ok_or_else(|| AppError("Missing connectionId".to_string()))?;
|
||||||
|
let database = database.ok_or_else(|| AppError("Missing database".to_string()))?;
|
||||||
|
let bucket = bucket.ok_or_else(|| AppError("Missing bucket".to_string()))?;
|
||||||
|
let file_name = file_name.ok_or_else(|| AppError("Missing fileName".to_string()))?;
|
||||||
|
let file_bytes = file_bytes.ok_or_else(|| AppError("No file uploaded".to_string()))?;
|
||||||
|
|
||||||
|
ensure_writable(&state.app, &connection_id, "Upload GridFS file").await?;
|
||||||
|
let result = dbx_core::document_ops::upload_gridfs_file_core(
|
||||||
|
&state.app,
|
||||||
|
&connection_id,
|
||||||
|
&database,
|
||||||
|
&bucket,
|
||||||
|
&file_name,
|
||||||
|
&file_bytes,
|
||||||
|
content_type.as_deref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(AppError)?;
|
||||||
|
Ok(Json(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_gridfs_file(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Json(req): Json<GridFsFileDeleteRequest>,
|
||||||
|
) -> Result<Json<()>, AppError> {
|
||||||
|
ensure_writable(&state.app, &req.connection_id, "Delete GridFS file").await?;
|
||||||
|
dbx_core::document_ops::delete_gridfs_file_core(
|
||||||
|
&state.app,
|
||||||
|
&req.connection_id,
|
||||||
|
&req.database,
|
||||||
|
&req.bucket,
|
||||||
|
&req.file_id,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(AppError)?;
|
||||||
|
Ok(Json(()))
|
||||||
|
}
|
||||||
@@ -356,6 +356,24 @@ test("restores MQ tabs with selected tenant context", () => {
|
|||||||
assert.equal(restored.tabs[0]?.mqTenant, "public");
|
assert.equal(restored.tabs[0]?.mqTenant, "public");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("restores GridFS manager tabs with their mode intact", () => {
|
||||||
|
const raw = JSON.stringify([
|
||||||
|
queryTab({
|
||||||
|
id: "gridfs",
|
||||||
|
title: "GridFS",
|
||||||
|
mode: "mongo-gridfs" as QueryTab["mode"],
|
||||||
|
sql: "",
|
||||||
|
database: "amazon",
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const restored = restoreOpenTabsState(raw, "gridfs");
|
||||||
|
|
||||||
|
assert.equal(restored.tabs[0]?.mode, "mongo-gridfs");
|
||||||
|
assert.equal(restored.tabs[0]?.title, "GridFS");
|
||||||
|
assert.equal(restored.activeTabId, "gridfs");
|
||||||
|
});
|
||||||
|
|
||||||
test("query-only restore keeps legacy query tabs without a mode", () => {
|
test("query-only restore keeps legacy query tabs without a mode", () => {
|
||||||
const raw = JSON.stringify([
|
const raw = JSON.stringify([
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -59,6 +59,50 @@ test("mongo tabs target the matching visible collection node", () => {
|
|||||||
assert.equal(findSidebarNodeForActiveTab(tab, [flat(collection)])?.id, "events-node");
|
assert.equal(findSidebarNodeForActiveTab(tab, [flat(collection)])?.id, "events-node");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("GridFS tabs target the shared GridFS sidebar entry", () => {
|
||||||
|
const managerTab: QueryTab = {
|
||||||
|
id: "tab-gridfs",
|
||||||
|
title: "GridFS",
|
||||||
|
connectionId: "conn-1",
|
||||||
|
database: "app",
|
||||||
|
sql: "",
|
||||||
|
isExecuting: false,
|
||||||
|
mode: "mongo-gridfs" as QueryTab["mode"],
|
||||||
|
};
|
||||||
|
const bucketTab: QueryTab = {
|
||||||
|
id: "tab-bucket",
|
||||||
|
title: "app.receipts",
|
||||||
|
connectionId: "conn-1",
|
||||||
|
database: "app",
|
||||||
|
sql: "receipts",
|
||||||
|
isExecuting: false,
|
||||||
|
mode: "mongo-bucket",
|
||||||
|
mongoBucket: {
|
||||||
|
bucketName: "receipts",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const gridFsNode: TreeNode = {
|
||||||
|
id: "gridfs-node",
|
||||||
|
label: "GridFS",
|
||||||
|
type: "mongo-gridfs" as TreeNode["type"],
|
||||||
|
connectionId: "conn-1",
|
||||||
|
database: "app",
|
||||||
|
};
|
||||||
|
|
||||||
|
assert.deepEqual(activeTabSidebarTarget(managerTab), {
|
||||||
|
type: "mongo-gridfs",
|
||||||
|
connectionId: "conn-1",
|
||||||
|
database: "app",
|
||||||
|
});
|
||||||
|
assert.deepEqual(activeTabSidebarTarget(bucketTab), {
|
||||||
|
type: "mongo-gridfs",
|
||||||
|
connectionId: "conn-1",
|
||||||
|
database: "app",
|
||||||
|
});
|
||||||
|
assert.equal(findSidebarNodeForActiveTab(managerTab, [flat(gridFsNode)])?.id, "gridfs-node");
|
||||||
|
assert.equal(findSidebarNodeForActiveTab(bucketTab, [flat(gridFsNode)])?.id, "gridfs-node");
|
||||||
|
});
|
||||||
|
|
||||||
test("MQ tabs with a selected tenant target the matching tenant node", () => {
|
test("MQ tabs with a selected tenant target the matching tenant node", () => {
|
||||||
const tab: QueryTab = {
|
const tab: QueryTab = {
|
||||||
id: "tab-1",
|
id: "tab-1",
|
||||||
|
|||||||
@@ -19,6 +19,26 @@ test("reorders cached MongoDB collections alphabetically", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("keeps MongoDB GridFS entry before collections", () => {
|
||||||
|
const parent: Pick<TreeNode, "type"> = { type: "mongo-db" };
|
||||||
|
const children: TreeNode[] = [
|
||||||
|
{ id: "c:db:movies", label: "movies", type: "mongo-collection" },
|
||||||
|
{ id: "c:db:__gridfs", label: "GridFS", type: "mongo-gridfs" as TreeNode["type"] },
|
||||||
|
{ id: "c:db:comments", label: "comments", type: "mongo-collection" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const sorted = sortSidebarTreeChildrenForParent(parent, children, "mongodb");
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
sorted.map((child) => [child.type, child.label]),
|
||||||
|
[
|
||||||
|
["mongo-gridfs", "GridFS"],
|
||||||
|
["mongo-collection", "comments"],
|
||||||
|
["mongo-collection", "movies"],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test("keeps SQL Server object groups first and sorts schema children after them", () => {
|
test("keeps SQL Server object groups first and sorts schema children after them", () => {
|
||||||
const parent: Pick<TreeNode, "type"> = { type: "database" };
|
const parent: Pick<TreeNode, "type"> = { type: "database" };
|
||||||
const children: TreeNode[] = [
|
const children: TreeNode[] = [
|
||||||
|
|||||||
@@ -135,6 +135,45 @@ test("zookeeper tabs use key browser labels", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("GridFS tabs use dedicated titles and labels", () => {
|
||||||
|
const restoreStorage = installMemoryStorage();
|
||||||
|
setActivePinia(createPinia());
|
||||||
|
useConnectionStore().addEphemeralConnection({
|
||||||
|
...conn("conn-1"),
|
||||||
|
name: "uat-mongo",
|
||||||
|
db_type: "mongodb",
|
||||||
|
port: 27017,
|
||||||
|
});
|
||||||
|
const t = (key: string) => {
|
||||||
|
if (key === "tabs.gridfs") return "GridFS";
|
||||||
|
if (key === "tabs.mongo") return "Mongo";
|
||||||
|
return key;
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const managerTab = queryTab({
|
||||||
|
title: "GridFS",
|
||||||
|
database: "amazon",
|
||||||
|
mode: "mongo-gridfs" as QueryTab["mode"],
|
||||||
|
sql: "",
|
||||||
|
});
|
||||||
|
const bucketTab = queryTab({
|
||||||
|
title: "amazon.NMDocumentData_acc001",
|
||||||
|
database: "amazon",
|
||||||
|
mode: "mongo-bucket",
|
||||||
|
sql: "NMDocumentData_acc001",
|
||||||
|
mongoBucket: { bucketName: "NMDocumentData_acc001" },
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(tabDisplayTitle(managerTab, t), "GridFS@amazon");
|
||||||
|
assert.equal(tabDisplayTitle(bucketTab, t), "NMDocumentData_acc001@amazon");
|
||||||
|
assert.equal(tabModeLabel(managerTab, t), "GridFS");
|
||||||
|
assert.equal(tabModeLabel(bucketTab, t), "GridFS");
|
||||||
|
} finally {
|
||||||
|
restoreStorage();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("tabular result items hide statement results without returned columns", () => {
|
test("tabular result items hide statement results without returned columns", () => {
|
||||||
const results = [result([]), result(["id"]), result([]), result(["name"])];
|
const results = [result([]), result(["id"]), result([]), result(["name"])];
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { test } from "vitest";
|
import { test } from "vitest";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { copyNameForTreeNode, objectSourceKindForTreeNode, shouldRunTreeNodeRowAction, sidebarSelectionCopyAction, treeNodeRowAction, treeNodeRowDoubleClickAction } from "../../apps/desktop/src/lib/treeNodeClick.ts";
|
import { copyNameForTreeNode, isDocumentBrowserTreeNode, objectSourceKindForTreeNode, shouldRunTreeNodeRowAction, sidebarSelectionCopyAction, treeNodeRowAction, treeNodeRowDoubleClickAction } from "../../apps/desktop/src/lib/treeNodeClick.ts";
|
||||||
|
|
||||||
test("table and view rows open data without toggling structure groups", () => {
|
test("table and view rows open data without toggling structure groups", () => {
|
||||||
assert.equal(treeNodeRowAction("table", true), "open-data");
|
assert.equal(treeNodeRowAction("table", true), "open-data");
|
||||||
@@ -40,7 +40,15 @@ test("leaf data browser nodes keep their open behavior through toggle handler",
|
|||||||
assert.equal(treeNodeRowAction("redis-db", false), "toggle");
|
assert.equal(treeNodeRowAction("redis-db", false), "toggle");
|
||||||
assert.equal(treeNodeRowAction("etcd-root", false), "toggle");
|
assert.equal(treeNodeRowAction("etcd-root", false), "toggle");
|
||||||
assert.equal(treeNodeRowAction("zookeeper-root", false), "toggle");
|
assert.equal(treeNodeRowAction("zookeeper-root", false), "toggle");
|
||||||
|
assert.equal(treeNodeRowAction("mongo-gridfs" as never, false), "toggle");
|
||||||
assert.equal(treeNodeRowAction("mongo-collection", false), "toggle");
|
assert.equal(treeNodeRowAction("mongo-collection", false), "toggle");
|
||||||
|
assert.equal(treeNodeRowAction("mongo-bucket", false), "toggle");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("document browser helper covers Mongo collections and GridFS buckets", () => {
|
||||||
|
assert.equal(isDocumentBrowserTreeNode("mongo-collection"), true);
|
||||||
|
assert.equal(isDocumentBrowserTreeNode("mongo-bucket"), true);
|
||||||
|
assert.equal(isDocumentBrowserTreeNode("redis-db"), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("repeated clicks continue to toggle expandable rows", () => {
|
test("repeated clicks continue to toggle expandable rows", () => {
|
||||||
|
|||||||
@@ -129,3 +129,90 @@ pub async fn document_delete_document(
|
|||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn document_list_gridfs_buckets(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
connection_id: String,
|
||||||
|
database: String,
|
||||||
|
) -> Result<Vec<dbx_core::document_ops::MongoGridFsBucketInfo>, String> {
|
||||||
|
dbx_core::document_ops::list_gridfs_buckets_core(&state, &connection_id, &database).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn document_create_gridfs_bucket(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
connection_id: String,
|
||||||
|
database: String,
|
||||||
|
bucket: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
ensure_connection_writable(&state, &connection_id, "Create GridFS bucket").await?;
|
||||||
|
dbx_core::document_ops::create_gridfs_bucket_core(&state, &connection_id, &database, &bucket).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn document_delete_gridfs_bucket(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
connection_id: String,
|
||||||
|
database: String,
|
||||||
|
bucket: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
ensure_connection_writable(&state, &connection_id, "Delete GridFS bucket").await?;
|
||||||
|
dbx_core::document_ops::delete_gridfs_bucket_core(&state, &connection_id, &database, &bucket).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn document_list_gridfs_files(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
connection_id: String,
|
||||||
|
database: String,
|
||||||
|
bucket: String,
|
||||||
|
) -> Result<Vec<dbx_core::document_ops::MongoGridFsFileInfo>, String> {
|
||||||
|
dbx_core::document_ops::list_gridfs_files_core(&state, &connection_id, &database, &bucket).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn document_download_gridfs_file(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
connection_id: String,
|
||||||
|
database: String,
|
||||||
|
bucket: String,
|
||||||
|
file_id: String,
|
||||||
|
) -> Result<Vec<u8>, String> {
|
||||||
|
dbx_core::document_ops::download_gridfs_file_core(&state, &connection_id, &database, &bucket, &file_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn document_upload_gridfs_file(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
connection_id: String,
|
||||||
|
database: String,
|
||||||
|
bucket: String,
|
||||||
|
file_name: String,
|
||||||
|
data: Vec<u8>,
|
||||||
|
content_type: Option<String>,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
ensure_connection_writable(&state, &connection_id, "Upload GridFS file").await?;
|
||||||
|
dbx_core::document_ops::upload_gridfs_file_core(
|
||||||
|
&state,
|
||||||
|
&connection_id,
|
||||||
|
&database,
|
||||||
|
&bucket,
|
||||||
|
&file_name,
|
||||||
|
&data,
|
||||||
|
content_type.as_deref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn document_delete_gridfs_file(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
connection_id: String,
|
||||||
|
database: String,
|
||||||
|
bucket: String,
|
||||||
|
file_id: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
ensure_connection_writable(&state, &connection_id, "Delete GridFS file").await?;
|
||||||
|
dbx_core::document_ops::delete_gridfs_file_core(&state, &connection_id, &database, &bucket, &file_id).await
|
||||||
|
}
|
||||||
@@ -943,6 +943,13 @@ pub fn run() {
|
|||||||
commands::document_cmd::document_list_databases,
|
commands::document_cmd::document_list_databases,
|
||||||
commands::document_cmd::document_list_collections,
|
commands::document_cmd::document_list_collections,
|
||||||
commands::document_cmd::document_find_documents,
|
commands::document_cmd::document_find_documents,
|
||||||
|
commands::document_cmd::document_list_gridfs_buckets,
|
||||||
|
commands::document_cmd::document_create_gridfs_bucket,
|
||||||
|
commands::document_cmd::document_delete_gridfs_bucket,
|
||||||
|
commands::document_cmd::document_list_gridfs_files,
|
||||||
|
commands::document_cmd::document_download_gridfs_file,
|
||||||
|
commands::document_cmd::document_upload_gridfs_file,
|
||||||
|
commands::document_cmd::document_delete_gridfs_file,
|
||||||
commands::mongo_cmd::mongo_find_documents,
|
commands::mongo_cmd::mongo_find_documents,
|
||||||
commands::mongo_cmd::mongo_server_version,
|
commands::mongo_cmd::mongo_server_version,
|
||||||
commands::mongo_cmd::mongo_aggregate_documents,
|
commands::mongo_cmd::mongo_aggregate_documents,
|
||||||
|
|||||||
Reference in new issue
Block a user