Merge branch 'main' of https://github.com/Abeautifulsnow/dbx into feat/ai-agent-loop-phase1
This commit is contained in:
Generated
+1
@@ -1906,6 +1906,7 @@ dependencies = [
|
||||
"log",
|
||||
"mongodb",
|
||||
"mysql_async",
|
||||
"pageant",
|
||||
"percent-encoding",
|
||||
"portpicker",
|
||||
"rayon",
|
||||
|
||||
@@ -121,6 +121,8 @@ const newQueryContextSource = ref<"tab" | "sidebar">("tab");
|
||||
const showSaveSqlDialog = ref(false);
|
||||
const saveSqlName = ref("");
|
||||
const saveSqlFolderId = ref("");
|
||||
const pendingSaveAndCloseTabId = ref<string | null>(null);
|
||||
const pendingPrevActiveTabId = ref<string | null>(null);
|
||||
const ROOT_SAVED_SQL_FOLDER = "__root__";
|
||||
|
||||
const activeTab = computed(() => queryStore.tabs.find((t) => t.id === queryStore.activeTabId));
|
||||
@@ -185,12 +187,15 @@ async function resolveActiveExecutableSql() {
|
||||
: "";
|
||||
}
|
||||
|
||||
const blockDangerousRedisCommands = ref(true);
|
||||
|
||||
const { dangerSql, pendingDangerSql, showDangerDialog, suppressDangerConfirm, tryExecute, doExecute, cancelActiveExecution, tryExplain, onDangerConfirm, explainMode } = useSqlExecution({
|
||||
activeTab,
|
||||
activeConnection,
|
||||
executableSql,
|
||||
resolveExecutableSql: resolveActiveExecutableSql,
|
||||
activeOutputView,
|
||||
blockDangerousRedisCommands,
|
||||
});
|
||||
|
||||
const dialogs = useDialogSources();
|
||||
@@ -218,7 +223,19 @@ const connectionStats = computed(() => ({
|
||||
}));
|
||||
const recentConnections = computed(() => connectionStore.connections.slice(0, 5));
|
||||
const savedSqlHistoryItems = computed(() => {
|
||||
const folderById = new Map(savedSqlStore.allFolders.map((folder) => [folder.id, folder.name]));
|
||||
const folderById = new Map(savedSqlStore.allFolders.map((folder) => [folder.id, folder]));
|
||||
const folderPath = (folderId?: string): string | undefined => {
|
||||
if (!folderId) return undefined;
|
||||
const parts: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
let folder = folderById.get(folderId);
|
||||
while (folder && !seen.has(folder.id)) {
|
||||
seen.add(folder.id);
|
||||
parts.unshift(folder.name);
|
||||
folder = folder.parentFolderId ? folderById.get(folder.parentFolderId) : undefined;
|
||||
}
|
||||
return parts.join("/");
|
||||
};
|
||||
return rankSavedSqlHistory(savedSqlStore.allFiles, { limit: 6 }).map((file) => {
|
||||
const connection = connectionStore.getConfig(file.connectionId);
|
||||
return {
|
||||
@@ -226,13 +243,25 @@ const savedSqlHistoryItems = computed(() => {
|
||||
name: file.name,
|
||||
connectionName: connection ? connectionRedactedNameLabel(connection) : t("welcome.unknownConnection"),
|
||||
database: file.database,
|
||||
folderName: file.folderId ? folderById.get(file.folderId) : undefined,
|
||||
folderName: folderPath(file.folderId),
|
||||
openCount: file.openCount ?? 0,
|
||||
};
|
||||
});
|
||||
});
|
||||
const saveSqlFolders = computed(() => {
|
||||
return savedSqlStore.allFolders;
|
||||
const folderById = new Map(savedSqlStore.allFolders.map((folder) => [folder.id, folder]));
|
||||
const pathForFolder = (folderId: string) => {
|
||||
const parts: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
let folder = folderById.get(folderId);
|
||||
while (folder && !seen.has(folder.id)) {
|
||||
seen.add(folder.id);
|
||||
parts.unshift(folder.name);
|
||||
folder = folder.parentFolderId ? folderById.get(folder.parentFolderId) : undefined;
|
||||
}
|
||||
return parts.join(" / ");
|
||||
};
|
||||
return savedSqlStore.allFoldersTreeOrder.map((folder) => ({ ...folder, displayName: pathForFolder(folder.id) || folder.name }));
|
||||
});
|
||||
|
||||
async function applyUiScale(scale: number) {
|
||||
@@ -363,6 +392,36 @@ function defaultSavedSqlName(title: string) {
|
||||
return normalized.endsWith(".sql") ? normalized : `${normalized}.sql`;
|
||||
}
|
||||
|
||||
async function handleSaveTab(tabId: string) {
|
||||
const tab = queryStore.tabs.find((t) => t.id === tabId);
|
||||
if (!tab || !tab.sql.trim()) return;
|
||||
const existing = tab.savedSqlId ? savedSqlStore.getFile(tab.savedSqlId) : undefined;
|
||||
if (existing) {
|
||||
const updated = await savedSqlStore.saveFile({
|
||||
id: existing.id,
|
||||
connectionId: tab.connectionId,
|
||||
folderId: existing.folderId,
|
||||
name: existing.name,
|
||||
database: tab.database,
|
||||
schema: tab.schema,
|
||||
sql: tab.sql,
|
||||
});
|
||||
queryStore.linkSavedSql(tab.id, updated.id, updated.name);
|
||||
queryStore.markTabClean(tab);
|
||||
toast(t("savedSql.saved"), 2000);
|
||||
queryStore.closeTab(tabId, { force: true });
|
||||
return;
|
||||
}
|
||||
// No existing saved SQL — open save dialog, then close after save
|
||||
const prevActive = queryStore.activeTabId;
|
||||
queryStore.activeTabId = tabId;
|
||||
saveSqlName.value = defaultSavedSqlName(tab.title);
|
||||
saveSqlFolderId.value = ROOT_SAVED_SQL_FOLDER;
|
||||
pendingSaveAndCloseTabId.value = tabId;
|
||||
pendingPrevActiveTabId.value = prevActive;
|
||||
showSaveSqlDialog.value = true;
|
||||
}
|
||||
|
||||
async function openSaveSqlDialog() {
|
||||
const tab = activeTab.value;
|
||||
if (!tab || !tab.sql.trim()) return;
|
||||
@@ -432,7 +491,15 @@ async function confirmSaveSqlToLibrary() {
|
||||
sql: tab.sql,
|
||||
});
|
||||
queryStore.linkSavedSql(tab.id, saved.id, saved.name);
|
||||
queryStore.markTabClean(tab);
|
||||
showSaveSqlDialog.value = false;
|
||||
if (pendingSaveAndCloseTabId.value) {
|
||||
const closeId = pendingSaveAndCloseTabId.value;
|
||||
pendingSaveAndCloseTabId.value = null;
|
||||
if (pendingPrevActiveTabId.value) queryStore.activeTabId = pendingPrevActiveTabId.value;
|
||||
pendingPrevActiveTabId.value = null;
|
||||
queryStore.closeTab(closeId, { force: true });
|
||||
}
|
||||
toast(t("savedSql.saved"), 2000);
|
||||
} catch (e: any) {
|
||||
toast(t("savedSql.saveFailed", { message: e?.message || String(e) }), 5000);
|
||||
@@ -1029,7 +1096,7 @@ onUnmounted(() => {
|
||||
|
||||
<div :class="isClassicLayout ? 'flex-1 min-w-0 overflow-hidden' : 'flex-1 min-w-0 overflow-hidden rounded-md border border-border/80 bg-background'">
|
||||
<div class="h-full flex flex-col min-w-0">
|
||||
<AppTabBar :show-driver-store="showDriverStore" :agent-driver-update-count="toolbarAgentDriverUpdateCount" @toggle-driver-store="showDriverStore = true" @close-driver-store="showDriverStore = false" />
|
||||
<AppTabBar :show-driver-store="showDriverStore" :agent-driver-update-count="toolbarAgentDriverUpdateCount" @toggle-driver-store="showDriverStore = true" @close-driver-store="showDriverStore = false" @save-tab="handleSaveTab" />
|
||||
<DriverStorePage v-if="showDriverStore" class="flex-1 min-h-0" :update-notifications-enabled="updateNotificationsEnabled" @update-count-change="updateAgentDriverUpdateCount" />
|
||||
<div v-else-if="activeTab" class="flex flex-col flex-1 min-h-0">
|
||||
<EditorToolbar
|
||||
@@ -1038,7 +1105,9 @@ onUnmounted(() => {
|
||||
:active-connection="activeConnection"
|
||||
:executable-sql="executableSql"
|
||||
:explain-mode="explainMode"
|
||||
:block-dangerous-redis-commands="blockDangerousRedisCommands"
|
||||
@update:explain-mode="(m: 'explain' | 'autotrace') => (explainMode = m)"
|
||||
@update:block-dangerous-redis-commands="(v: boolean) => (blockDangerousRedisCommands = v)"
|
||||
@execute="tryExecute()"
|
||||
@cancel="cancelActiveExecution()"
|
||||
@explain="tryExplain()"
|
||||
@@ -1190,7 +1259,15 @@ onUnmounted(() => {
|
||||
</Transition>
|
||||
</div>
|
||||
|
||||
<Dialog v-model:open="showSaveSqlDialog">
|
||||
<Dialog
|
||||
:open="showSaveSqlDialog"
|
||||
@update:open="
|
||||
(open: boolean) => {
|
||||
showSaveSqlDialog = open;
|
||||
if (!open) pendingSaveAndCloseTabId = null;
|
||||
}
|
||||
"
|
||||
>
|
||||
<DialogContent class="sm:max-w-[420px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ t("savedSql.saveToLibrary") }}</DialogTitle>
|
||||
@@ -1209,14 +1286,21 @@ onUnmounted(() => {
|
||||
<SelectContent position="popper">
|
||||
<SelectItem :value="ROOT_SAVED_SQL_FOLDER">{{ t("savedSql.rootFolder") }}</SelectItem>
|
||||
<SelectItem v-for="folder in saveSqlFolders" :key="folder.id" :value="folder.id">
|
||||
{{ folder.name }}
|
||||
{{ folder.displayName }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="showSaveSqlDialog = false">{{ t("dangerDialog.cancel") }}</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
@click="
|
||||
showSaveSqlDialog = false;
|
||||
pendingSaveAndCloseTabId = null;
|
||||
"
|
||||
>{{ t("dangerDialog.cancel") }}</Button
|
||||
>
|
||||
<Button :disabled="!saveSqlName.trim()" @click="confirmSaveSqlToLibrary">{{ t("savedSql.save") }}</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -12,7 +12,7 @@ const props = defineProps<{
|
||||
<circle class="text-green-600 transition-[stroke-dashoffset] duration-200" cx="16" cy="16" r="13" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" pathLength="100" stroke-dasharray="100" :stroke-dashoffset="100 - (props.percent ?? 0)" />
|
||||
</svg>
|
||||
<span class="relative z-10 font-mono text-[10px] font-semibold leading-none text-green-700 tabular-nums">
|
||||
{{ props.percent ?? "..." }}
|
||||
{{ props.percent ?? 0 }}
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Activity, ExternalLink, Cpu, FolderOpen, MemoryStick, Search, Square, T
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import DriverInstallProgressCircle from "@/components/config/DriverInstallProgressCircle.vue";
|
||||
@@ -12,7 +13,7 @@ import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
import { isTauriRuntime } from "@/lib/tauriRuntime";
|
||||
import { countAvailableDriverUpdates } from "@/lib/agentDriverUpdateBadge";
|
||||
import type { JdbcDriverInfo, JdbcPluginStatus } from "@/types/database";
|
||||
import type { JdbcDriverInfo, JdbcMavenBundleInfo, JdbcPluginStatus } from "@/types/database";
|
||||
import * as api from "@/lib/api";
|
||||
import type { AgentDriverInfo, DriverRuntimeInfo, DriverRuntimeSummary, DriverStoreUsage, JavaRuntimeConfig } from "@/lib/api";
|
||||
import { formatRuntimeBytes, formatRuntimeCpu, formatRuntimeUptime, runtimeHealthClass, runtimeStatusClass, runtimeStatusDotClass } from "@/lib/driverRuntimePresentation";
|
||||
@@ -63,6 +64,7 @@ const DRIVER_RUNTIME_POLL_MS = 5000;
|
||||
const OFFLINE_DRIVER_DOWNLOAD_URL = "https://dbxio.com/cn/drivers";
|
||||
|
||||
let unlisten: (() => void) | null = null;
|
||||
const lastProgressPercent = ref<number | null>(null);
|
||||
|
||||
const installedJres = computed(() => {
|
||||
const jreMap = new Map<string, boolean>();
|
||||
@@ -78,16 +80,28 @@ const progressText = computed(() => {
|
||||
const p = progress.value;
|
||||
if (!p) return "";
|
||||
if (p.step === "jre-extract") return t("driverStore.progressJreExtract");
|
||||
const label = p.step === "jre" ? t("driverStore.progressDownloadJre") : t("driverStore.progressDownloadDriver");
|
||||
if (p.step === "jdbc-plugin-extract") return t("driverStore.progressJdbcPluginExtract");
|
||||
const label = p.step === "jre" ? t("driverStore.progressDownloadJre") : p.step === "jdbc-plugin" ? t("driverStore.progressDownloadJdbcPlugin") : t("driverStore.progressDownloadDriver");
|
||||
if (!p.total) return `${label}...`;
|
||||
const pct = Math.round(((p.downloaded ?? 0) / p.total) * 100);
|
||||
const dl = formatSize(p.downloaded ?? 0);
|
||||
const total = formatSize(p.total);
|
||||
const prefix = upgradingAll.value && upgradingCurrent.value ? `[${upgradingIndex.value}/${upgradingTotal.value}] ${upgradingCurrent.value} — ` : "";
|
||||
const prefix = upgradingAll.value && upgradingCurrent.value ? `[${upgradingIndex.value}/${upgradingTotal.value}] ${upgradingCurrent.value} - ` : "";
|
||||
return `${prefix}${label} ${dl} / ${total} (${pct}%)`;
|
||||
});
|
||||
|
||||
const progressNumber = computed(() => driverInstallProgressPercent(progress.value));
|
||||
const progressNumber = computed(() => {
|
||||
const next = driverInstallProgressPercent(progress.value);
|
||||
if (next !== null) {
|
||||
lastProgressPercent.value = next;
|
||||
}
|
||||
return next ?? lastProgressPercent.value;
|
||||
});
|
||||
|
||||
function resetInstallProgress() {
|
||||
progress.value = null;
|
||||
lastProgressPercent.value = null;
|
||||
}
|
||||
|
||||
const updatableCount = computed(() => (props.updateNotificationsEnabled ? drivers.value.filter((d) => d.update_available).length : 0));
|
||||
const usageSummary = computed(() => {
|
||||
@@ -231,7 +245,7 @@ async function installDriver(dbType: string) {
|
||||
async function runDriverInstall(dbType: string) {
|
||||
const label = drivers.value.find((d) => d.db_type === dbType)?.label ?? dbType;
|
||||
installing.value = dbType;
|
||||
progress.value = null;
|
||||
resetInstallProgress();
|
||||
try {
|
||||
const blockers = await api.checkAgentUpdateBlockers([dbType]);
|
||||
if (blockers.length > 0) {
|
||||
@@ -245,7 +259,7 @@ async function runDriverInstall(dbType: string) {
|
||||
toast(t("driverStore.driverInstallFailed", { label, error: e }));
|
||||
} finally {
|
||||
installing.value = null;
|
||||
progress.value = null;
|
||||
resetInstallProgress();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,7 +277,7 @@ async function runQueuedDriverInstalls() {
|
||||
async function upgradeAll() {
|
||||
upgradingAll.value = true;
|
||||
queuedDriverInstalls.value = [];
|
||||
progress.value = null;
|
||||
resetInstallProgress();
|
||||
try {
|
||||
const updatableDbTypes = drivers.value.filter((driver) => driver.update_available).map((driver) => driver.db_type);
|
||||
const blockers = await api.checkAgentUpdateBlockers(updatableDbTypes);
|
||||
@@ -286,7 +300,7 @@ async function upgradeAll() {
|
||||
upgradingCurrent.value = "";
|
||||
upgradingIndex.value = 0;
|
||||
upgradingTotal.value = 0;
|
||||
progress.value = null;
|
||||
resetInstallProgress();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,7 +371,7 @@ async function importOfflineZip() {
|
||||
}
|
||||
if (!selected) return;
|
||||
importingZip.value = true;
|
||||
progress.value = null;
|
||||
resetInstallProgress();
|
||||
try {
|
||||
const count = await api.importAgentsFromZip(selected);
|
||||
await refreshAgents();
|
||||
@@ -366,7 +380,7 @@ async function importOfflineZip() {
|
||||
toast(t("driverStore.offlineImportFailed", { error: e }));
|
||||
} finally {
|
||||
importingZip.value = false;
|
||||
progress.value = null;
|
||||
resetInstallProgress();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -402,7 +416,7 @@ async function importDriverJar(dbType: string) {
|
||||
|
||||
async function reinstallJre(jreKey: string) {
|
||||
reinstallingJre.value = jreKey;
|
||||
progress.value = null;
|
||||
resetInstallProgress();
|
||||
try {
|
||||
await api.reinstallJre(jreKey);
|
||||
await refreshAgents();
|
||||
@@ -411,7 +425,7 @@ async function reinstallJre(jreKey: string) {
|
||||
toast(t("driverStore.jreReinstallFailed", { jre: jreKey, error: e }));
|
||||
} finally {
|
||||
reinstallingJre.value = null;
|
||||
progress.value = null;
|
||||
resetInstallProgress();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,12 +448,45 @@ function formatSize(bytes: number): string {
|
||||
// ──────────── JDBC drivers ────────────
|
||||
|
||||
const jdbcDrivers = ref<JdbcDriverInfo[]>([]);
|
||||
const jdbcMavenBundles = ref<JdbcMavenBundleInfo[]>([]);
|
||||
const jdbcDriverSearch = ref("");
|
||||
const isLoadingJdbcDrivers = ref(false);
|
||||
const jdbcPluginStatus = ref<JdbcPluginStatus | null>(null);
|
||||
const isInstallingJdbcPlugin = ref(false);
|
||||
const isUninstallingJdbcPlugin = ref(false);
|
||||
const jdbcDriverPathInput = ref("");
|
||||
const jdbcMavenCoordinateInput = ref("");
|
||||
const jdbcMavenRepository = ref("https://repo.maven.apache.org/maven2/");
|
||||
const customJdbcMavenRepository = ref("");
|
||||
const isInstallingJdbcMavenDriver = ref(false);
|
||||
|
||||
const jdbcMavenRepositoryOptions = [
|
||||
{ label: "Maven Central", value: "https://repo.maven.apache.org/maven2/" },
|
||||
{ label: "Aliyun", value: "https://maven.aliyun.com/repository/public" },
|
||||
{ label: "Huawei Cloud", value: "https://repo.huaweicloud.com/repository/maven" },
|
||||
{ label: "Tencent Cloud", value: "https://mirrors.cloud.tencent.com/nexus/repository/maven-public" },
|
||||
{ label: "Custom", value: "custom" },
|
||||
];
|
||||
|
||||
type JdbcDriverListItem =
|
||||
| {
|
||||
kind: "manual";
|
||||
id: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
source: string;
|
||||
size: number;
|
||||
driver: JdbcDriverInfo;
|
||||
}
|
||||
| {
|
||||
kind: "maven";
|
||||
id: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
source: string;
|
||||
size: number;
|
||||
bundle: JdbcMavenBundleInfo;
|
||||
};
|
||||
|
||||
const filteredAgentDrivers = computed(() => {
|
||||
const query = agentDriverSearch.value.trim().toLowerCase();
|
||||
@@ -447,10 +494,34 @@ const filteredAgentDrivers = computed(() => {
|
||||
return drivers.value.filter((driver) => [driver.label, driver.db_type, driver.version, driver.installed_version, driver.jre].filter(Boolean).join(" ").toLowerCase().includes(query));
|
||||
});
|
||||
|
||||
const jdbcDriverListItems = computed<JdbcDriverListItem[]>(() => {
|
||||
const bundleItems = jdbcMavenBundles.value.map((bundle) => ({
|
||||
kind: "maven" as const,
|
||||
id: `maven:${bundle.id}`,
|
||||
title: bundle.coordinate,
|
||||
subtitle: `${bundle.artifacts.length} JARs - ${bundle.repositories.join(", ")}`,
|
||||
source: t("driverStore.jdbcSourceMaven"),
|
||||
size: bundle.artifacts.reduce((total, artifact) => total + Number(artifact.size || 0), 0),
|
||||
bundle,
|
||||
}));
|
||||
const manualItems = jdbcDrivers.value
|
||||
.filter((driver) => !driver.bundle_id)
|
||||
.map((driver) => ({
|
||||
kind: "manual" as const,
|
||||
id: `manual:${driver.path}`,
|
||||
title: driver.name,
|
||||
subtitle: driver.path,
|
||||
source: t("driverStore.jdbcSourceManual"),
|
||||
size: driver.size,
|
||||
driver,
|
||||
}));
|
||||
return [...bundleItems, ...manualItems].sort((a, b) => a.title.localeCompare(b.title));
|
||||
});
|
||||
|
||||
const filteredJdbcDrivers = computed(() => {
|
||||
const query = jdbcDriverSearch.value.trim().toLowerCase();
|
||||
if (!query) return jdbcDrivers.value;
|
||||
return jdbcDrivers.value.filter((driver) => [driver.name, driver.path, String(driver.size)].join(" ").toLowerCase().includes(query));
|
||||
if (!query) return jdbcDriverListItems.value;
|
||||
return jdbcDriverListItems.value.filter((item) => [item.title, item.subtitle, String(item.size)].join(" ").toLowerCase().includes(query));
|
||||
});
|
||||
|
||||
function formatBytes(bytes: number) {
|
||||
@@ -568,7 +639,9 @@ function jreUsageLabel(key: string) {
|
||||
async function loadJdbcDrivers() {
|
||||
isLoadingJdbcDrivers.value = true;
|
||||
try {
|
||||
jdbcDrivers.value = await api.listJdbcDrivers();
|
||||
const [drivers, bundles] = await Promise.all([api.listJdbcDrivers(), api.listJdbcMavenBundles()]);
|
||||
jdbcDrivers.value = drivers;
|
||||
jdbcMavenBundles.value = bundles;
|
||||
} catch (e: any) {
|
||||
toast(String(e?.message || e), 5000);
|
||||
} finally {
|
||||
@@ -597,6 +670,7 @@ async function loadJdbcPluginStatus() {
|
||||
async function installJdbcPlugin() {
|
||||
if (isInstallingJdbcPlugin.value) return;
|
||||
isInstallingJdbcPlugin.value = true;
|
||||
resetInstallProgress();
|
||||
try {
|
||||
jdbcPluginStatus.value = await api.installJdbcPlugin();
|
||||
emitDriverUpdateCount();
|
||||
@@ -606,6 +680,7 @@ async function installJdbcPlugin() {
|
||||
toast(String(e?.message || e), 5000);
|
||||
} finally {
|
||||
isInstallingJdbcPlugin.value = false;
|
||||
resetInstallProgress();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -697,6 +772,24 @@ async function importJdbcDriverPathInput() {
|
||||
await importJdbcDriverPaths(paths);
|
||||
}
|
||||
|
||||
async function installJdbcMavenDriver() {
|
||||
const coordinate = jdbcMavenCoordinateInput.value.trim();
|
||||
const repository = jdbcMavenRepository.value === "custom" ? customJdbcMavenRepository.value.trim() : jdbcMavenRepository.value;
|
||||
if (!coordinate || !repository || isInstallingJdbcMavenDriver.value) return;
|
||||
isInstallingJdbcMavenDriver.value = true;
|
||||
try {
|
||||
jdbcDrivers.value = await api.installJdbcDriverFromMaven(coordinate, [repository]);
|
||||
jdbcMavenBundles.value = await api.listJdbcMavenBundles();
|
||||
jdbcMavenCoordinateInput.value = "";
|
||||
void loadDriverStoreUsage();
|
||||
toast(t("driverStore.jdbcMavenInstallSuccess"));
|
||||
} catch (e: any) {
|
||||
toast(String(e?.message || e), 8000);
|
||||
} finally {
|
||||
isInstallingJdbcMavenDriver.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteJdbcDriver(path: string) {
|
||||
try {
|
||||
jdbcDrivers.value = await api.deleteJdbcDriver(path);
|
||||
@@ -707,6 +800,17 @@ async function deleteJdbcDriver(path: string) {
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteJdbcMavenBundle(bundleId: string) {
|
||||
try {
|
||||
jdbcDrivers.value = await api.deleteJdbcMavenBundle(bundleId);
|
||||
jdbcMavenBundles.value = await api.listJdbcMavenBundles();
|
||||
void loadDriverStoreUsage();
|
||||
toast(t("settings.jdbcDeleteSuccess"));
|
||||
} catch (e: any) {
|
||||
toast(String(e?.message || e), 5000);
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────── Lifecycle ────────────
|
||||
|
||||
onMounted(async () => {
|
||||
@@ -961,6 +1065,7 @@ watch(driverStoreTab, (tab) => {
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-3">
|
||||
<DriverInstallProgressCircle v-if="isInstallingJdbcPlugin" :percent="progressNumber" :title="progressTitle(t('driverStore.progressDownloadJdbcPlugin'))" />
|
||||
<span v-if="jdbcPluginStatus?.installed" class="text-xs" :class="jdbcPluginStatus.compatible ? 'text-green-600' : 'text-destructive'">
|
||||
{{
|
||||
jdbcPluginStatus.compatible
|
||||
@@ -1007,26 +1112,50 @@ watch(driverStoreTab, (tab) => {
|
||||
{{ t("settings.jdbcImport") }}
|
||||
</Button>
|
||||
</div>
|
||||
<div class="grid gap-2 md:grid-cols-[minmax(0,1fr)_180px_auto]">
|
||||
<Input v-model="jdbcMavenCoordinateInput" class="h-8 text-xs" :placeholder="t('driverStore.jdbcMavenCoordinatePlaceholder')" @keydown.enter.prevent="installJdbcMavenDriver" />
|
||||
<Select v-model="jdbcMavenRepository">
|
||||
<SelectTrigger class="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="repo in jdbcMavenRepositoryOptions" :key="repo.value" :value="repo.value">
|
||||
{{ repo.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button class="h-8 shrink-0 rounded-full" :disabled="!jdbcMavenCoordinateInput.trim() || isInstallingJdbcMavenDriver || (jdbcMavenRepository === 'custom' && !customJdbcMavenRepository.trim())" @click="installJdbcMavenDriver">
|
||||
<Loader2 v-if="isInstallingJdbcMavenDriver" class="h-4 w-4 animate-spin" />
|
||||
<Download v-else class="h-4 w-4" />
|
||||
{{ t("driverStore.jdbcMavenInstall") }}
|
||||
</Button>
|
||||
</div>
|
||||
<Input v-if="jdbcMavenRepository === 'custom'" v-model="customJdbcMavenRepository" class="h-8 text-xs" placeholder="https://repo.example.com/repository/maven-public" @keydown.enter.prevent="installJdbcMavenDriver" />
|
||||
</div>
|
||||
|
||||
<div class="rounded-md border">
|
||||
<div v-if="isLoadingJdbcDrivers" class="p-4 text-sm text-muted-foreground">
|
||||
{{ t("common.loading") }}
|
||||
</div>
|
||||
<div v-else-if="jdbcDrivers.length === 0" class="p-4 text-sm text-muted-foreground">
|
||||
<div v-else-if="jdbcDriverListItems.length === 0" class="p-4 text-sm text-muted-foreground">
|
||||
{{ t("settings.jdbcNoDrivers") }}
|
||||
</div>
|
||||
<div v-else-if="filteredJdbcDrivers.length === 0" class="p-4 text-sm text-muted-foreground">
|
||||
{{ t("driverStore.noMatchingDrivers") }}
|
||||
</div>
|
||||
<div v-else class="divide-y">
|
||||
<div v-for="driver in filteredJdbcDrivers" :key="driver.path" class="flex items-center gap-3 p-3">
|
||||
<div v-for="item in filteredJdbcDrivers" :key="item.id" class="flex items-center gap-3 p-3">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="truncate text-sm font-medium">{{ driver.name }}</div>
|
||||
<div class="truncate text-xs text-muted-foreground">{{ driver.path }}</div>
|
||||
<div class="flex min-w-0 items-center gap-2">
|
||||
<div class="truncate text-sm font-medium">{{ item.title }}</div>
|
||||
<Badge variant="outline" class="h-5 shrink-0 rounded-full px-2 text-[10px] font-medium">
|
||||
{{ item.source }}
|
||||
</Badge>
|
||||
</div>
|
||||
<div class="truncate text-xs text-muted-foreground">{{ item.subtitle }}</div>
|
||||
</div>
|
||||
<div class="shrink-0 text-xs text-muted-foreground">{{ formatBytes(driver.size) }}</div>
|
||||
<Button variant="ghost" size="icon" class="h-8 w-8 shrink-0 rounded-full" @click="deleteJdbcDriver(driver.path)">
|
||||
<div class="shrink-0 text-xs text-muted-foreground">{{ formatBytes(item.size) }}</div>
|
||||
<Button variant="ghost" size="icon" class="h-8 w-8 shrink-0 rounded-full" @click="item.kind === 'maven' ? deleteJdbcMavenBundle(item.bundle.id) : deleteJdbcDriver(item.driver.path)">
|
||||
<Trash2 class="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -4,13 +4,15 @@ import { uuid } from "@/lib/utils";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import type { ConnectionConfig, DatabaseType, JdbcDriverInfo, ProxyTunnelConfig, SshTunnelConfig, TransportLayerConfig } from "@/types/database";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import type { ConnectionConfig, DatabaseType, JdbcDriverInfo, JdbcMavenBundleInfo, ProxyTunnelConfig, SshTunnelConfig, TransportLayerConfig } from "@/types/database";
|
||||
import { useConnectionStore } from "@/stores/connectionStore";
|
||||
import { useSettingsStore } from "@/stores/settingsStore";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
@@ -33,6 +35,11 @@ type DbCategory = { key: string; title: string; options: DbOption[] };
|
||||
type DialogStep = "select" | "config";
|
||||
type DbPickerView = "icon" | "list";
|
||||
type ConfigTab = "connection" | "advanced" | "tls" | "transport";
|
||||
type JdbcDriverSelectItem = {
|
||||
id: string;
|
||||
label: string;
|
||||
paths: string[];
|
||||
};
|
||||
|
||||
type LegacyTransportFields = {
|
||||
ssh_enabled?: boolean;
|
||||
@@ -246,8 +253,10 @@ const customDriverName = ref("");
|
||||
const mongoUseUrl = ref(false);
|
||||
const jdbcDriverPathsInput = ref("");
|
||||
const jdbcDrivers = ref<JdbcDriverInfo[]>([]);
|
||||
const jdbcMavenBundles = ref<JdbcMavenBundleInfo[]>([]);
|
||||
const agentDrivers = ref<AgentDriverInstallState[]>([]);
|
||||
const selectedJdbcDriverPath = ref("");
|
||||
const jdbcManualClasspathOpen = ref(false);
|
||||
const connectionUrlInput = ref("");
|
||||
const oceanbaseSubMode = ref<"mysql" | "oracle">("mysql");
|
||||
const h2ConnectionMode = ref<H2ConnectionMode>("file");
|
||||
@@ -270,6 +279,31 @@ const isPresetColor = (color: string | undefined) => colorOptions.some((c) => c.
|
||||
const customColorInput = ref("");
|
||||
const customColorOpen = ref(false);
|
||||
|
||||
const jdbcDriverSelectItems = computed<JdbcDriverSelectItem[]>(() => {
|
||||
const bundles = jdbcMavenBundles.value.map((bundle) => ({
|
||||
id: `maven:${bundle.id}`,
|
||||
label: bundle.coordinate,
|
||||
paths: bundle.artifacts.map((artifact) => artifact.path),
|
||||
}));
|
||||
const manual = jdbcDrivers.value
|
||||
.filter((driver) => !driver.bundle_id)
|
||||
.map((driver) => ({
|
||||
id: `manual:${driver.path}`,
|
||||
label: driver.name,
|
||||
paths: [driver.path],
|
||||
}));
|
||||
return [...bundles, ...manual].sort((left, right) => left.label.localeCompare(right.label));
|
||||
});
|
||||
|
||||
const jdbcDriverSelectItemById = computed(() => new Map(jdbcDriverSelectItems.value.map((item) => [item.id, item])));
|
||||
const jdbcManualClasspathCount = computed(
|
||||
() =>
|
||||
jdbcDriverPathsInput.value
|
||||
.split(/\r?\n/)
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean).length,
|
||||
);
|
||||
|
||||
function applyCustomColor(value: string) {
|
||||
form.value.color = value;
|
||||
customColorInput.value = value;
|
||||
@@ -727,7 +761,7 @@ const iconTypeMap: Record<string, string> = {
|
||||
custom_postgres: "postgres",
|
||||
};
|
||||
|
||||
const dbOptions = [
|
||||
const dbOptions: DbOption[] = [
|
||||
{ value: "postgres", label: "PostgreSQL" },
|
||||
{ value: "mysql", label: "MySQL" },
|
||||
{ value: "mongodb", label: "MongoDB" },
|
||||
@@ -787,12 +821,19 @@ const dbOptions = [
|
||||
{ value: "influxdb", label: "InfluxDB" },
|
||||
{ value: "iris", label: "IRIS" },
|
||||
{ value: "jdbc", label: "JDBC" },
|
||||
{ value: "custom_mysql", label: "Custom (MySQL)" },
|
||||
{ value: "custom_postgres", label: "Custom (PostgreSQL)" },
|
||||
];
|
||||
|
||||
const dbCategories = computed<DbCategory[]>(() => [{ key: "all", title: "", options: dbOptions }]);
|
||||
|
||||
function matchesDbOption(option: DbOption, keyword: string, categoryTitle = "") {
|
||||
const profile = driverProfiles[option.value];
|
||||
return [option.label, option.value, profile?.label, profile?.type, categoryTitle].some((value) =>
|
||||
String(value || "")
|
||||
.toLowerCase()
|
||||
.includes(keyword),
|
||||
);
|
||||
}
|
||||
|
||||
const filteredDbCategories = computed<DbCategory[]>(() => {
|
||||
const keyword = dbSearchQuery.value.trim().toLowerCase();
|
||||
if (!keyword) return dbCategories.value;
|
||||
@@ -800,14 +841,7 @@ const filteredDbCategories = computed<DbCategory[]>(() => {
|
||||
return dbCategories.value
|
||||
.map((category) => ({
|
||||
...category,
|
||||
options: category.options.filter((option) => {
|
||||
const profile = driverProfiles[option.value];
|
||||
return [option.label, option.value, profile?.label, profile?.type, category.title].some((value) =>
|
||||
String(value || "")
|
||||
.toLowerCase()
|
||||
.includes(keyword),
|
||||
);
|
||||
}),
|
||||
options: category.options.filter((option) => matchesDbOption(option, keyword, category.title)),
|
||||
}))
|
||||
.filter((category) => category.options.length > 0);
|
||||
});
|
||||
@@ -1939,9 +1973,12 @@ async function browseJdbcDriverPaths() {
|
||||
async function loadJdbcDrivers() {
|
||||
if (!isDesktop) return;
|
||||
try {
|
||||
jdbcDrivers.value = await api.listJdbcDrivers();
|
||||
const [drivers, bundles] = await Promise.all([api.listJdbcDrivers(), api.listJdbcMavenBundles()]);
|
||||
jdbcDrivers.value = drivers;
|
||||
jdbcMavenBundles.value = bundles;
|
||||
} catch {
|
||||
jdbcDrivers.value = [];
|
||||
jdbcMavenBundles.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1962,18 +1999,21 @@ async function loadAgentDrivers() {
|
||||
}
|
||||
}
|
||||
|
||||
function addJdbcDriverPath(path: string) {
|
||||
function addJdbcDriverPaths(paths: string[]) {
|
||||
const existing = jdbcDriverPathsInput.value
|
||||
.split(/\r?\n/)
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
jdbcDriverPathsInput.value = Array.from(new Set([...existing, path])).join("\n");
|
||||
jdbcDriverPathsInput.value = Array.from(new Set([...existing, ...paths])).join("\n");
|
||||
}
|
||||
|
||||
function onJdbcDriverSelect(path: any) {
|
||||
if (typeof path !== "string" || !path) return;
|
||||
selectedJdbcDriverPath.value = path;
|
||||
addJdbcDriverPath(path);
|
||||
function onJdbcDriverSelect(id: any) {
|
||||
if (typeof id !== "string" || !id) return;
|
||||
const item = jdbcDriverSelectItemById.value.get(id);
|
||||
if (!item) return;
|
||||
selectedJdbcDriverPath.value = id;
|
||||
addJdbcDriverPaths(item.paths);
|
||||
jdbcManualClasspathOpen.value = false;
|
||||
}
|
||||
|
||||
function openExternalUrl(url: string) {
|
||||
@@ -2014,7 +2054,7 @@ function openExternalUrl(url: string) {
|
||||
<div class="max-h-[58vh] space-y-5 overflow-y-auto pr-2">
|
||||
<section v-for="category in filteredDbCategories" :key="category.key" class="space-y-2">
|
||||
<div class="flex items-center">
|
||||
<h3 class="text-sm font-medium">{{ category.title }}</h3>
|
||||
<h3 v-if="category.title" class="text-sm font-medium">{{ category.title }}</h3>
|
||||
</div>
|
||||
|
||||
<div v-if="dbPickerView === 'icon'" class="grid grid-cols-2 gap-2 sm:grid-cols-4 lg:grid-cols-5">
|
||||
@@ -2200,24 +2240,29 @@ function openExternalUrl(url: string) {
|
||||
<Label class="text-right">{{ t("connection.password") }}</Label>
|
||||
<Input v-model="form.password" type="password" class="col-span-3" />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label class="text-right">{{ t("connection.jdbcDriverClass") }}</Label>
|
||||
<Input v-model="form.jdbc_driver_class" class="col-span-3" :placeholder="t('connection.jdbcDriverClassPlaceholder')" />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-start gap-4">
|
||||
<Label class="text-right mt-2">{{ t("connection.jdbcDriverPaths") }}</Label>
|
||||
<div class="col-span-3 space-y-2">
|
||||
<Select v-if="jdbcDrivers.length > 0" :model-value="selectedJdbcDriverPath" @update:model-value="onJdbcDriverSelect">
|
||||
<Select v-if="jdbcDriverSelectItems.length > 0" :model-value="selectedJdbcDriverPath" @update:model-value="onJdbcDriverSelect">
|
||||
<SelectTrigger>
|
||||
<SelectValue :placeholder="t('connection.jdbcDriverSelectPlaceholder')" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="driver in jdbcDrivers" :key="driver.path" :value="driver.path">
|
||||
{{ driver.name }}
|
||||
<SelectItem v-for="driver in jdbcDriverSelectItems" :key="driver.id" :value="driver.id">
|
||||
{{ driver.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div class="flex items-start gap-1">
|
||||
<div class="flex items-center justify-between gap-3 rounded-md border bg-muted/20 px-3 py-2">
|
||||
<div class="flex min-w-0 items-center gap-2">
|
||||
<div class="truncate text-xs font-medium">{{ t("connection.jdbcManualClasspath") }}</div>
|
||||
<Badge variant="outline" class="h-5 shrink-0 rounded-full px-2 text-[10px] font-medium">
|
||||
{{ t("connection.jdbcManualClasspathCount", { count: jdbcManualClasspathCount }) }}
|
||||
</Badge>
|
||||
</div>
|
||||
<Switch v-model="jdbcManualClasspathOpen" />
|
||||
</div>
|
||||
<div v-if="jdbcManualClasspathOpen" class="flex items-start gap-1">
|
||||
<textarea
|
||||
v-model="jdbcDriverPathsInput"
|
||||
class="flex min-h-12 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
@@ -2234,6 +2279,10 @@ function openExternalUrl(url: string) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label class="text-right">{{ t("connection.jdbcDriverClass") }}</Label>
|
||||
<Input v-model="form.jdbc_driver_class" class="col-span-3" :placeholder="t('connection.jdbcDriverClassPlaceholder')" />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-start gap-4">
|
||||
<span />
|
||||
<div class="col-span-3 space-y-2">
|
||||
|
||||
+181
-167
@@ -9,14 +9,17 @@ import { Input } from "@/components/ui/input";
|
||||
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
|
||||
import ErrorBanner from "@/components/ui/ErrorBanner.vue";
|
||||
import DataGrid from "@/components/grid/DataGrid.vue";
|
||||
import * as api from "@/lib/api";
|
||||
import { clampSearchSplitWidth } from "@/lib/dataGridSearchSplit";
|
||||
import { buildDocumentFilterCondition, combineDocumentFilterConditions, currentDocumentFilterJson, defaultDocumentFilterRule, documentFilterModeNeedsValue, documentFilterModeOptions, documentStoreProviderFor, type DocumentFilterMode, type DocumentFilterRule } from "@/lib/documentStoreProvider";
|
||||
import { normalizeResultPageSize } from "@/lib/paginationPageSize";
|
||||
import { useSettingsStore } from "@/stores/settingsStore";
|
||||
import JsonEditNode from "./JsonEditNode.vue";
|
||||
import type { EditNode } from "@/types/editor";
|
||||
import type { DatabaseType, QueryResult } from "@/types/database";
|
||||
import type { CustomSaveHandler } from "@/composables/useDataGridEditor";
|
||||
import { Splitpanes, Pane } from "splitpanes";
|
||||
import "splitpanes/dist/splitpanes.css";
|
||||
|
||||
@@ -60,22 +63,16 @@ const tableFindPaneWidth = ref<number | null>(null);
|
||||
const isResizingTableSearchSplit = ref(false);
|
||||
let tableSearchSplitStartX = 0;
|
||||
let tableSearchSplitStartWidth = 0;
|
||||
const documentStoreProvider = computed(() => documentStoreProviderFor(props.databaseType));
|
||||
|
||||
const tableFindPaneStyle = computed(() => {
|
||||
if (tableFindPaneWidth.value == null) return {};
|
||||
return { flex: `0 0 ${tableFindPaneWidth.value}px` };
|
||||
});
|
||||
const documentStoreLabels = computed(() =>
|
||||
props.databaseType === "elasticsearch"
|
||||
? {
|
||||
documentsLabel: "Documents",
|
||||
queryPreview: `${props.collection}/_search`,
|
||||
}
|
||||
: {
|
||||
documentsLabel: t("mongo.documents", { count: total.value }),
|
||||
queryPreview: mongoQueryPreview.value,
|
||||
},
|
||||
);
|
||||
const documentStoreLabels = computed(() => ({
|
||||
documentsLabel: documentStoreProvider.value.documentsLabel({ total: total.value, t }),
|
||||
queryPreview: documentQueryPreview.value,
|
||||
}));
|
||||
|
||||
type PendingDelete = { kind: "document"; index: number } | { kind: "field"; index: number; name: string };
|
||||
type LocalFilterSummary = {
|
||||
@@ -84,28 +81,9 @@ type LocalFilterSummary = {
|
||||
values: string[];
|
||||
hiddenValueCount: number;
|
||||
};
|
||||
type MongoFilterMode = "equals" | "not-equals" | "like" | "not-like" | "greater-than" | "less-than" | "is-null" | "is-not-null";
|
||||
type MongoFilterRule = {
|
||||
id: string;
|
||||
fieldName: string;
|
||||
mode: MongoFilterMode;
|
||||
rawValue: string;
|
||||
conjunction: "AND" | "OR";
|
||||
};
|
||||
|
||||
const mongoFilterModeOptions: Array<{ value: MongoFilterMode; labelKey: string }> = [
|
||||
{ value: "equals", labelKey: "grid.filterBuilderEquals" },
|
||||
{ value: "not-equals", labelKey: "grid.filterBuilderNotEquals" },
|
||||
{ value: "like", labelKey: "grid.filterBuilderContains" },
|
||||
{ value: "not-like", labelKey: "grid.filterBuilderNotContains" },
|
||||
{ value: "greater-than", labelKey: "grid.filterBuilderGreaterThan" },
|
||||
{ value: "less-than", labelKey: "grid.filterBuilderLessThan" },
|
||||
{ value: "is-null", labelKey: "grid.filterBuilderIsNull" },
|
||||
{ value: "is-not-null", labelKey: "grid.filterBuilderIsNotNull" },
|
||||
];
|
||||
const mongoFilterBuilderOpen = ref(false);
|
||||
const mongoFilterRules = ref<MongoFilterRule[]>([]);
|
||||
const appliedMongoFilter = ref<Record<string, unknown> | null>(null);
|
||||
const documentFilterBuilderOpen = ref(false);
|
||||
const documentFilterRules = ref<DocumentFilterRule[]>([]);
|
||||
const appliedDocumentFilter = ref<Record<string, unknown> | null>(null);
|
||||
|
||||
const pendingDelete = ref<PendingDelete | null>(null);
|
||||
|
||||
@@ -165,139 +143,77 @@ const gridResult = computed<QueryResult>(() => {
|
||||
|
||||
return { columns, rows, affected_rows: 0, execution_time_ms: 0, truncated: false };
|
||||
});
|
||||
const mongoFilterFieldOptions = computed(() => gridResult.value.columns);
|
||||
const mongoStructuredFilterCount = computed(() => (appliedMongoFilter.value ? 1 : 0));
|
||||
const documentFilterFieldOptions = computed(() => gridResult.value.columns);
|
||||
const documentStructuredFilterCount = computed(() => (appliedDocumentFilter.value ? 1 : 0));
|
||||
|
||||
function defaultMongoFilterRule(): MongoFilterRule {
|
||||
return {
|
||||
id: uuid(),
|
||||
fieldName: mongoFilterFieldOptions.value[0] ?? "",
|
||||
mode: "equals",
|
||||
rawValue: "",
|
||||
conjunction: "AND",
|
||||
};
|
||||
function createDocumentFilterRule(): DocumentFilterRule {
|
||||
return defaultDocumentFilterRule(uuid(), documentFilterFieldOptions.value[0] ?? "");
|
||||
}
|
||||
|
||||
function ensureMongoFilterRule() {
|
||||
if (mongoFilterRules.value.length === 0 && mongoFilterFieldOptions.value.length > 0) {
|
||||
mongoFilterRules.value = [defaultMongoFilterRule()];
|
||||
function ensureDocumentFilterRule() {
|
||||
if (documentFilterRules.value.length === 0 && documentFilterFieldOptions.value.length > 0) {
|
||||
documentFilterRules.value = [createDocumentFilterRule()];
|
||||
}
|
||||
}
|
||||
|
||||
function addMongoFilterRule() {
|
||||
ensureMongoFilterRule();
|
||||
mongoFilterRules.value = [...mongoFilterRules.value, defaultMongoFilterRule()];
|
||||
function addDocumentFilterRule() {
|
||||
ensureDocumentFilterRule();
|
||||
documentFilterRules.value = [...documentFilterRules.value, createDocumentFilterRule()];
|
||||
}
|
||||
|
||||
function removeMongoFilterRule(ruleId: string) {
|
||||
mongoFilterRules.value = mongoFilterRules.value.filter((rule) => rule.id !== ruleId);
|
||||
if (mongoFilterRules.value.length === 0) appliedMongoFilter.value = null;
|
||||
function removeDocumentFilterRule(ruleId: string) {
|
||||
documentFilterRules.value = documentFilterRules.value.filter((rule) => rule.id !== ruleId);
|
||||
if (documentFilterRules.value.length === 0) appliedDocumentFilter.value = null;
|
||||
}
|
||||
|
||||
function updateMongoFilterRule(ruleId: string, patch: Partial<MongoFilterRule>) {
|
||||
mongoFilterRules.value = mongoFilterRules.value.map((rule) => {
|
||||
function updateDocumentFilterRule(ruleId: string, patch: Partial<DocumentFilterRule>) {
|
||||
documentFilterRules.value = documentFilterRules.value.map((rule) => {
|
||||
if (rule.id !== ruleId) return rule;
|
||||
const next = { ...rule, ...patch };
|
||||
if (!mongoFilterModeNeedsValue(next.mode)) next.rawValue = "";
|
||||
if (!documentFilterModeNeedsValue(next.mode)) next.rawValue = "";
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function resetMongoFilterBuilder() {
|
||||
appliedMongoFilter.value = null;
|
||||
mongoFilterRules.value = mongoFilterFieldOptions.value.length > 0 ? [defaultMongoFilterRule()] : [];
|
||||
function resetDocumentFilterBuilder() {
|
||||
appliedDocumentFilter.value = null;
|
||||
documentFilterRules.value = documentFilterFieldOptions.value.length > 0 ? [createDocumentFilterRule()] : [];
|
||||
}
|
||||
|
||||
function mongoFilterModeNeedsValue(mode: MongoFilterMode): boolean {
|
||||
return mode !== "is-null" && mode !== "is-not-null";
|
||||
function currentDocumentFilter(): string | undefined {
|
||||
return currentDocumentFilterJson(filterInput.value, appliedDocumentFilter.value);
|
||||
}
|
||||
|
||||
function parseMongoFilterValue(raw: string): unknown {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return "";
|
||||
try {
|
||||
return JSON.parse(trimmed);
|
||||
} catch {
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
|
||||
function mongoConditionForRule(rule: MongoFilterRule): Record<string, unknown> | null {
|
||||
if (!rule.fieldName) return null;
|
||||
if (mongoFilterModeNeedsValue(rule.mode) && !rule.rawValue.trim()) return null;
|
||||
const value = mongoFilterModeNeedsValue(rule.mode) ? parseMongoFilterValue(rule.rawValue) : null;
|
||||
switch (rule.mode) {
|
||||
case "equals":
|
||||
return { [rule.fieldName]: value };
|
||||
case "not-equals":
|
||||
return { [rule.fieldName]: { $ne: value } };
|
||||
case "like":
|
||||
return { [rule.fieldName]: { $regex: String(value), $options: "i" } };
|
||||
case "not-like":
|
||||
return { [rule.fieldName]: { $not: { $regex: String(value), $options: "i" } } };
|
||||
case "greater-than":
|
||||
return { [rule.fieldName]: { $gt: value } };
|
||||
case "less-than":
|
||||
return { [rule.fieldName]: { $lt: value } };
|
||||
case "is-null":
|
||||
return { [rule.fieldName]: null };
|
||||
case "is-not-null":
|
||||
return { [rule.fieldName]: { $ne: null } };
|
||||
}
|
||||
}
|
||||
|
||||
function combineMongoConditions(conditions: Record<string, unknown>[], rules: MongoFilterRule[]): Record<string, unknown> | null {
|
||||
if (conditions.length === 0) return null;
|
||||
let result = conditions[0];
|
||||
for (let i = 1; i < conditions.length; i++) {
|
||||
const operator = rules[i]?.conjunction === "OR" ? "$or" : "$and";
|
||||
result = { [operator]: [result, conditions[i]] };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseMongoFilterInput(): Record<string, unknown> {
|
||||
const trimmed = filterInput.value.trim();
|
||||
if (!trimmed) return {};
|
||||
const parsed = JSON.parse(trimmed);
|
||||
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};
|
||||
}
|
||||
|
||||
function currentMongoFilter(): string | undefined {
|
||||
const manual = parseMongoFilterInput();
|
||||
const structured = appliedMongoFilter.value;
|
||||
const filter = structured ? (Object.keys(manual).length ? { $and: [manual, structured] } : structured) : manual;
|
||||
return Object.keys(filter).length ? JSON.stringify(filter) : undefined;
|
||||
}
|
||||
|
||||
const mongoQueryPreview = computed(() => {
|
||||
const documentQueryPreview = computed(() => {
|
||||
let filter = "{}";
|
||||
try {
|
||||
filter = currentMongoFilter() ?? "{}";
|
||||
filter = currentDocumentFilter() ?? "{}";
|
||||
} catch {
|
||||
filter = filterInput.value.trim() || "{}";
|
||||
}
|
||||
const sort = sortInput.value.trim();
|
||||
const parts = [`db.${props.collection}.find(${filter})`];
|
||||
if (sort) parts.push(`.sort(${sort})`);
|
||||
parts.push(`.skip(${page.value * pageSize.value}).limit(${pageSize.value})`);
|
||||
return parts.join("");
|
||||
return documentStoreProvider.value.queryPreview({
|
||||
collection: props.collection,
|
||||
filterJson: filter,
|
||||
sortJson: sortInput.value.trim(),
|
||||
skip: page.value * pageSize.value,
|
||||
limit: pageSize.value,
|
||||
});
|
||||
});
|
||||
|
||||
async function applyMongoStructuredFilters() {
|
||||
const items = mongoFilterRules.value.map((rule) => ({ rule, condition: mongoConditionForRule(rule) })).filter((item): item is { rule: MongoFilterRule; condition: Record<string, unknown> } => !!item.condition);
|
||||
const structured = combineMongoConditions(
|
||||
async function applyDocumentStructuredFilters() {
|
||||
const items = documentFilterRules.value.map((rule) => ({ rule, condition: buildDocumentFilterCondition(rule) })).filter((item): item is { rule: DocumentFilterRule; condition: Record<string, unknown> } => !!item.condition);
|
||||
const structured = combineDocumentFilterConditions(
|
||||
items.map((item) => item.condition),
|
||||
items.map((item) => item.rule),
|
||||
);
|
||||
appliedMongoFilter.value = structured;
|
||||
mongoFilterBuilderOpen.value = false;
|
||||
appliedDocumentFilter.value = structured;
|
||||
documentFilterBuilderOpen.value = false;
|
||||
applyFilter();
|
||||
}
|
||||
|
||||
function clearMongoFilters(clearLocalFilter?: (columnIndex?: number) => void) {
|
||||
appliedMongoFilter.value = null;
|
||||
resetMongoFilterBuilder();
|
||||
function clearDocumentFilters(clearLocalFilter?: (columnIndex?: number) => void) {
|
||||
appliedDocumentFilter.value = null;
|
||||
resetDocumentFilterBuilder();
|
||||
clearLocalFilter?.();
|
||||
applyFilter();
|
||||
}
|
||||
@@ -342,13 +258,117 @@ async function gridSave(changes: { dirtyRows: Map<number, Map<number, string | n
|
||||
await load();
|
||||
}
|
||||
|
||||
function formatMongoValue(val: unknown): string {
|
||||
if (val === null || val === undefined) return "null";
|
||||
if (typeof val === "number" || typeof val === "boolean") return String(val);
|
||||
if (typeof val === "string") return JSON.stringify(val);
|
||||
return JSON.stringify(val);
|
||||
}
|
||||
|
||||
function mongoIdPreview(val: unknown): string {
|
||||
if (val === null || val === undefined) return "null";
|
||||
if (typeof val === "string" && /^[a-fA-F0-9]{24}$/.test(val)) return `ObjectId("${val}")`;
|
||||
return formatMongoValue(val);
|
||||
}
|
||||
|
||||
function buildUpdateDoc(changes: Map<number, string | number | boolean | null>, columns: string[]): Record<string, unknown> {
|
||||
const setFields: Record<string, unknown> = {};
|
||||
const unsetFields: Record<string, unknown> = {};
|
||||
for (const [colIdx, newVal] of changes) {
|
||||
const col = columns[colIdx];
|
||||
if (!col || col === "_id") continue;
|
||||
if (newVal === null) {
|
||||
unsetFields[col] = "";
|
||||
} else if (typeof newVal === "string") {
|
||||
try {
|
||||
setFields[col] = JSON.parse(newVal);
|
||||
} catch {
|
||||
setFields[col] = newVal;
|
||||
}
|
||||
} else {
|
||||
setFields[col] = newVal;
|
||||
}
|
||||
}
|
||||
const doc: Record<string, unknown> = {};
|
||||
if (Object.keys(setFields).length > 0) doc.$set = setFields;
|
||||
if (Object.keys(unsetFields).length > 0) doc.$unset = unsetFields;
|
||||
return doc;
|
||||
}
|
||||
|
||||
function buildNewDoc(newRow: (string | number | boolean | null)[], columns: string[]): Record<string, unknown> {
|
||||
const doc: Record<string, unknown> = {};
|
||||
for (let ci = 0; ci < columns.length; ci++) {
|
||||
const col = columns[ci];
|
||||
if (!col || col === "_id") continue;
|
||||
const val = newRow[ci];
|
||||
if (val === null) continue;
|
||||
if (typeof val === "string") {
|
||||
try {
|
||||
doc[col] = JSON.parse(val);
|
||||
} catch {
|
||||
doc[col] = val;
|
||||
}
|
||||
} else {
|
||||
doc[col] = val;
|
||||
}
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
async function previewDocumentChanges(changes: { dirtyRows: Map<number, Map<number, string | number | boolean | null>>; deletedRows: Set<number>; newRows: (string | number | boolean | null)[][]; columns: string[]; rows: (string | number | boolean | null)[][] }): Promise<string[]> {
|
||||
const { dirtyRows, deletedRows, newRows, columns, rows } = changes;
|
||||
const idColIdx = columns.indexOf("_id");
|
||||
const stmts: string[] = [];
|
||||
const coll = props.collection;
|
||||
const isEs = documentStoreProvider.value.kind === "elasticsearch";
|
||||
|
||||
for (const [rowIdx, dirtyCols] of dirtyRows) {
|
||||
const row = rows[rowIdx];
|
||||
const id = row?.[idColIdx];
|
||||
if (id == null) continue;
|
||||
const updateDoc = buildUpdateDoc(dirtyCols, columns);
|
||||
if (isEs) {
|
||||
stmts.push(`POST /${coll}/_update/${JSON.stringify(String(id))}\n${JSON.stringify({ doc: updateDoc.$set ?? updateDoc }, null, 2)}`);
|
||||
} else {
|
||||
stmts.push(`db.${coll}.updateOne({_id: ${mongoIdPreview(id)}}, ${JSON.stringify(updateDoc)})`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const rowIdx of deletedRows) {
|
||||
const row = rows[rowIdx];
|
||||
const id = row?.[idColIdx];
|
||||
if (id == null) continue;
|
||||
if (isEs) {
|
||||
stmts.push(`DELETE /${coll}/_doc/${JSON.stringify(String(id))}`);
|
||||
} else {
|
||||
stmts.push(`db.${coll}.deleteOne({_id: ${mongoIdPreview(id)}})`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const newRow of newRows) {
|
||||
const doc = buildNewDoc(newRow, columns);
|
||||
if (isEs) {
|
||||
stmts.push(`POST /${coll}/_doc\n${JSON.stringify(doc, null, 2)}`);
|
||||
} else {
|
||||
stmts.push(`db.${coll}.insertOne(${JSON.stringify(doc)})`);
|
||||
}
|
||||
}
|
||||
|
||||
return stmts;
|
||||
}
|
||||
|
||||
const customSaveHandler = computed<CustomSaveHandler>(() => ({
|
||||
save: gridSave,
|
||||
preview: previewDocumentChanges,
|
||||
}));
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const filter = currentMongoFilter();
|
||||
const filter = currentDocumentFilter();
|
||||
const sort = sortInput.value.trim() || undefined;
|
||||
const result = await api.mongoFindDocuments(props.connectionId, props.database, props.collection, page.value * pageSize.value, pageSize.value, filter, sort);
|
||||
const result = await api.documentFindDocuments(props.connectionId, props.database, props.collection, page.value * pageSize.value, pageSize.value, filter, sort);
|
||||
const nextDocuments = result.documents.map(asRecord);
|
||||
documents.value = nextDocuments;
|
||||
if (nextDocuments.length > 0) {
|
||||
@@ -382,11 +402,7 @@ function paginate(offset: number, limit: number) {
|
||||
}
|
||||
|
||||
function onSort(column: string, _columnIndex: number, direction: "asc" | "desc" | null) {
|
||||
if (direction) {
|
||||
sortInput.value = JSON.stringify({ [column]: direction === "asc" ? 1 : -1 });
|
||||
} else {
|
||||
sortInput.value = "";
|
||||
}
|
||||
sortInput.value = documentStoreProvider.value.sortInputForColumn(column, direction);
|
||||
page.value = 0;
|
||||
load();
|
||||
}
|
||||
@@ -778,7 +794,7 @@ function resetTableSearchSplitWidth() {
|
||||
:result="gridResult"
|
||||
context="results"
|
||||
editable
|
||||
:custom-save="gridSave"
|
||||
:custom-save-handler="customSaveHandler"
|
||||
:loading="loading"
|
||||
:sql="documentStoreLabels.queryPreview"
|
||||
:page-offset="page * pageSize"
|
||||
@@ -791,24 +807,24 @@ function resetTableSearchSplitWidth() {
|
||||
<template #search-bar="{ localFilterCount, hasLocalColumnFilters, localFilterSummaries, clearLocalFilter }: { localFilterCount: number; hasLocalColumnFilters: boolean; localFilterSummaries: LocalFilterSummary[]; clearLocalFilter: (columnIndex?: number) => void }">
|
||||
<div ref="tableSearchSplitContainerRef" class="flex flex-1 min-w-0">
|
||||
<div class="flex flex-1 items-center gap-1 px-2 py-0.5 min-w-0" :style="tableFindPaneStyle">
|
||||
<Popover v-model:open="mongoFilterBuilderOpen">
|
||||
<Popover v-model:open="documentFilterBuilderOpen">
|
||||
<PopoverTrigger as-child>
|
||||
<button
|
||||
type="button"
|
||||
class="relative flex h-5 w-5 shrink-0 items-center justify-center rounded border text-[11px] font-medium transition-colors"
|
||||
:class="hasLocalColumnFilters || appliedMongoFilter ? 'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15' : 'border-border/70 text-muted-foreground hover:bg-accent hover:text-foreground'"
|
||||
@click="ensureMongoFilterRule"
|
||||
:class="hasLocalColumnFilters || appliedDocumentFilter ? 'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15' : 'border-border/70 text-muted-foreground hover:bg-accent hover:text-foreground'"
|
||||
@click="ensureDocumentFilterRule"
|
||||
>
|
||||
<Filter class="h-3 w-3" />
|
||||
<span v-if="localFilterCount + mongoStructuredFilterCount" class="absolute -right-1 -top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-primary px-1 text-[9px] leading-none text-primary-foreground">
|
||||
{{ localFilterCount + mongoStructuredFilterCount }}
|
||||
<span v-if="localFilterCount + documentStructuredFilterCount" class="absolute -right-1 -top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-primary px-1 text-[9px] leading-none text-primary-foreground">
|
||||
{{ localFilterCount + documentStructuredFilterCount }}
|
||||
</span>
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" class="w-[360px] max-w-[calc(100vw-24px)] gap-3 p-3">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="text-xs font-medium text-foreground">{{ t("grid.filter") }}</div>
|
||||
<Button variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="addMongoFilterRule">
|
||||
<Button variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="addDocumentFilterRule">
|
||||
<Plus class="mr-1 h-3.5 w-3.5" />
|
||||
{{ t("grid.filterBuilderAddRule") }}
|
||||
</Button>
|
||||
@@ -845,15 +861,15 @@ function resetTableSearchSplitWidth() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="mongoFilterRules.length" class="space-y-2">
|
||||
<template v-for="(rule, index) in mongoFilterRules" :key="rule.id">
|
||||
<div v-if="documentFilterRules.length" class="space-y-2">
|
||||
<template v-for="(rule, index) in documentFilterRules" :key="rule.id">
|
||||
<div v-if="index > 0" class="flex justify-center">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 px-2 text-[11px] font-medium text-muted-foreground hover:text-foreground"
|
||||
@click="
|
||||
updateMongoFilterRule(rule.id, {
|
||||
updateDocumentFilterRule(rule.id, {
|
||||
conjunction: rule.conjunction === 'AND' ? 'OR' : 'AND',
|
||||
})
|
||||
"
|
||||
@@ -862,41 +878,41 @@ function resetTableSearchSplitWidth() {
|
||||
</Button>
|
||||
</div>
|
||||
<div class="grid grid-cols-[minmax(0,1fr)_minmax(0,0.95fr)_minmax(0,1fr)_auto] items-center gap-1.5">
|
||||
<Select :model-value="rule.fieldName" @update:model-value="(value: any) => updateMongoFilterRule(rule.id, { fieldName: String(value) })">
|
||||
<Select :model-value="rule.fieldName" @update:model-value="(value: any) => updateDocumentFilterRule(rule.id, { fieldName: String(value) })">
|
||||
<SelectTrigger class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate">
|
||||
<SelectValue :placeholder="t('grid.filterBuilderColumn')" />
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper">
|
||||
<SelectItem v-for="fieldName in mongoFilterFieldOptions" :key="fieldName" :value="fieldName">
|
||||
<SelectItem v-for="fieldName in documentFilterFieldOptions" :key="fieldName" :value="fieldName">
|
||||
{{ fieldName }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select :model-value="rule.mode" @update:model-value="(value: any) => updateMongoFilterRule(rule.id, { mode: value as MongoFilterMode })">
|
||||
<Select :model-value="rule.mode" @update:model-value="(value: any) => updateDocumentFilterRule(rule.id, { mode: value as DocumentFilterMode })">
|
||||
<SelectTrigger class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper">
|
||||
<SelectItem v-for="option in mongoFilterModeOptions" :key="option.value" :value="option.value">
|
||||
<SelectItem v-for="option in documentFilterModeOptions" :key="option.value" :value="option.value">
|
||||
{{ t(option.labelKey) }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Input
|
||||
v-if="mongoFilterModeNeedsValue(rule.mode)"
|
||||
v-if="documentFilterModeNeedsValue(rule.mode)"
|
||||
:model-value="rule.rawValue"
|
||||
class="h-8 min-w-0 text-xs"
|
||||
:placeholder="t('grid.filterBuilderValue')"
|
||||
@update:model-value="(value) => updateMongoFilterRule(rule.id, { rawValue: String(value ?? '') })"
|
||||
@keydown.enter.prevent="applyMongoStructuredFilters"
|
||||
@update:model-value="(value) => updateDocumentFilterRule(rule.id, { rawValue: String(value ?? '') })"
|
||||
@keydown.enter.prevent="applyDocumentStructuredFilters"
|
||||
/>
|
||||
<div v-else class="flex h-8 min-w-0 items-center overflow-hidden rounded-md border border-dashed px-2 text-xs text-muted-foreground">
|
||||
<span class="truncate">{{ t("grid.filterBuilderNoValue") }}</span>
|
||||
</div>
|
||||
|
||||
<Button variant="ghost" size="icon" class="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive" :disabled="mongoFilterRules.length === 1" @click="removeMongoFilterRule(rule.id)">
|
||||
<Button variant="ghost" size="icon" class="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive" :disabled="documentFilterRules.length === 1" @click="removeDocumentFilterRule(rule.id)">
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -907,21 +923,21 @@ function resetTableSearchSplitWidth() {
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between gap-2 pt-1">
|
||||
<Button variant="ghost" size="sm" class="h-8 px-2 text-xs" @click="clearMongoFilters(clearLocalFilter)">
|
||||
<Button variant="ghost" size="sm" class="h-8 px-2 text-xs" @click="clearDocumentFilters(clearLocalFilter)">
|
||||
{{ t("grid.clearFilter") }}
|
||||
</Button>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button variant="ghost" size="sm" class="h-8 px-2 text-xs" @click="resetMongoFilterBuilder">
|
||||
<Button variant="ghost" size="sm" class="h-8 px-2 text-xs" @click="resetDocumentFilterBuilder">
|
||||
{{ t("grid.resetFilterBuilder") }}
|
||||
</Button>
|
||||
<Button size="sm" class="h-8 px-3 text-xs" @click="applyMongoStructuredFilters">
|
||||
<Button size="sm" class="h-8 px-3 text-xs" @click="applyDocumentStructuredFilters">
|
||||
{{ t("grid.applyFilter") }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<span class="text-blue-600 dark:text-blue-400 text-xs font-medium select-none shrink-0">find</span>
|
||||
<span class="text-blue-600 dark:text-blue-400 text-xs font-medium select-none shrink-0">{{ documentStoreProvider.filterInputLabel }}</span>
|
||||
<input v-model="filterInput" autocapitalize="off" autocorrect="off" spellcheck="false" class="flex-1 h-5 min-w-0 text-xs bg-transparent outline-none placeholder:text-muted-foreground/60 font-mono" placeholder="{}" @keydown.enter="applyFilter" />
|
||||
<button
|
||||
v-if="filterInput.trim()"
|
||||
@@ -937,14 +953,14 @@ function resetTableSearchSplitWidth() {
|
||||
<button
|
||||
type="button"
|
||||
class="group relative flex w-2 shrink-0 cursor-col-resize items-center justify-center border-l border-r border-border/80 bg-muted/15 hover:bg-primary/10 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
|
||||
aria-label="Resize find and sort"
|
||||
aria-label="Resize document filter and sort"
|
||||
@mousedown="startTableSearchSplitResize"
|
||||
@dblclick.stop="resetTableSearchSplitWidth"
|
||||
>
|
||||
<span class="h-5 w-px bg-border group-hover:bg-primary/60" />
|
||||
</button>
|
||||
<div class="flex flex-1 items-center gap-1 px-2 py-0.5 min-w-0">
|
||||
<span class="text-orange-600 dark:text-orange-400 text-xs font-medium select-none shrink-0">sort</span>
|
||||
<span class="text-orange-600 dark:text-orange-400 text-xs font-medium select-none shrink-0">{{ documentStoreProvider.sortInputLabel }}</span>
|
||||
<input v-model="sortInput" autocapitalize="off" autocorrect="off" spellcheck="false" class="flex-1 h-5 min-w-0 text-xs bg-transparent outline-none placeholder:text-muted-foreground/60 font-mono" placeholder="{}" @keydown.enter="applyFilter" />
|
||||
<button
|
||||
v-if="sortInput.trim()"
|
||||
@@ -1022,9 +1038,7 @@ function resetTableSearchSplitWidth() {
|
||||
{{ t("mongo.selectDocument") }}
|
||||
</div>
|
||||
|
||||
<div v-if="error" class="px-3 py-1.5 border-t bg-destructive/10 text-destructive text-xs shrink-0">
|
||||
{{ error }}
|
||||
</div>
|
||||
<ErrorBanner v-if="error" :message="error" />
|
||||
<DangerConfirmDialog v-model:open="showDeleteConfirm" :message="t('dangerDialog.deleteMessage')" :details="deleteDetails" :confirm-label="t('dangerDialog.deleteConfirm')" @confirm="confirmDelete" />
|
||||
</div>
|
||||
</Pane>
|
||||
@@ -181,6 +181,8 @@ let semanticDiagnosticTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let semanticDiagnosticRunId = 0;
|
||||
let editorIsActive = true;
|
||||
let tableReferenceDropListenerRegistered = false;
|
||||
let imeCompositionActive = false;
|
||||
let pendingImeModelEmit = false;
|
||||
|
||||
function editorThemeAppearance() {
|
||||
return isDark.value ? "dark" : "light";
|
||||
@@ -682,7 +684,7 @@ async function refreshSemanticDiagnostics() {
|
||||
setSemanticDiagnostics([]);
|
||||
return;
|
||||
}
|
||||
if (props.databaseType === "mongodb" || props.databaseType === "elasticsearch") {
|
||||
if (props.databaseType === "mongodb" || props.databaseType === "elasticsearch" || props.databaseType === "redis") {
|
||||
setSemanticDiagnostics([]);
|
||||
return;
|
||||
}
|
||||
@@ -904,6 +906,7 @@ async function provideElasticsearchCompletions(currentState: import("@codemirror
|
||||
}
|
||||
|
||||
async function provideSqlCompletions(currentState: import("@codemirror/state").EditorState, position: number, explicit: boolean) {
|
||||
if (imeCompositionActive || view.value?.compositionStarted || view.value?.composing) return null;
|
||||
if (!props.connectionId) return null;
|
||||
const fullDoc = currentState.doc.toString();
|
||||
if (props.databaseType === "elasticsearch") {
|
||||
@@ -990,6 +993,23 @@ async function provideSqlCompletions(currentState: import("@codemirror/state").E
|
||||
}
|
||||
}
|
||||
|
||||
function isEditorComposing(currentView: EditorViewType): boolean {
|
||||
return imeCompositionActive || currentView.compositionStarted || currentView.composing;
|
||||
}
|
||||
|
||||
function flushImeComposition() {
|
||||
const currentView = view.value;
|
||||
if (!currentView || !pendingImeModelEmit) return;
|
||||
pendingImeModelEmit = false;
|
||||
emit("update:modelValue", currentView.state.doc.toString());
|
||||
scheduleSemanticDiagnostics();
|
||||
syncContextMenuState(currentView);
|
||||
emit("selectionChange", selectedSqlFromView(currentView));
|
||||
emit("cursorChange", currentView.state.selection.main.head);
|
||||
latestSelection = readEditorSelection(currentView);
|
||||
if (editorIsActive) emitEditorSelection(latestSelection);
|
||||
}
|
||||
|
||||
function buildLocalSqlCompletionResult(completionContext: ReturnType<typeof getSqlCompletionContext>, fullDoc: string, position: number) {
|
||||
if (!props.connectionId || props.database == null) return null;
|
||||
const databaseNames = supportsDatabaseQualifierCompletion() && completionContext.suggestTables && !completionContext.insertTable ? connectionStore.lookupLocalCompletionDatabases(props.connectionId, completionContext.qualifier || completionContext.prefix, MAX_COMPLETION_TABLES) : [];
|
||||
@@ -1547,14 +1567,19 @@ onMounted(async () => {
|
||||
rectangularSelection({ eventFilter: (e: MouseEvent) => e.altKey || e.button === 1 }),
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged) {
|
||||
emit("update:modelValue", update.state.doc.toString());
|
||||
scheduleSemanticDiagnostics();
|
||||
let insertedText = "";
|
||||
update.changes.iterChanges((_fromA, _toA, _fromB, _toB, inserted) => {
|
||||
insertedText += inserted.toString();
|
||||
});
|
||||
if (insertedText.endsWith(".")) {
|
||||
startCompletion(update.view);
|
||||
if (isEditorComposing(update.view)) {
|
||||
pendingImeModelEmit = true;
|
||||
completionEpoch++;
|
||||
} else {
|
||||
emit("update:modelValue", update.state.doc.toString());
|
||||
scheduleSemanticDiagnostics();
|
||||
let insertedText = "";
|
||||
update.changes.iterChanges((_fromA, _toA, _fromB, _toB, inserted) => {
|
||||
insertedText += inserted.toString();
|
||||
});
|
||||
if (insertedText.endsWith(".")) {
|
||||
startCompletion(update.view);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (update.selectionSet || update.docChanged) {
|
||||
@@ -1586,6 +1611,16 @@ onMounted(async () => {
|
||||
if (editorIsActive) emitEditorSelection(latestSelection);
|
||||
return false;
|
||||
},
|
||||
compositionstart() {
|
||||
imeCompositionActive = true;
|
||||
completionEpoch++;
|
||||
return false;
|
||||
},
|
||||
compositionend() {
|
||||
imeCompositionActive = false;
|
||||
window.setTimeout(flushImeComposition, 0);
|
||||
return false;
|
||||
},
|
||||
wheel(event) {
|
||||
if (!event.metaKey && !event.ctrlKey) return false;
|
||||
event.preventDefault();
|
||||
@@ -1736,6 +1771,7 @@ watch(
|
||||
() => props.modelValue,
|
||||
(val) => {
|
||||
if (view.value && val !== view.value.state.doc.toString()) {
|
||||
if (isEditorComposing(view.value)) return;
|
||||
view.value.dispatch({
|
||||
changes: { from: 0, to: view.value.state.doc.length, insert: val },
|
||||
});
|
||||
|
||||
@@ -45,7 +45,6 @@ import {
|
||||
WrapText,
|
||||
Info,
|
||||
Rows3,
|
||||
TriangleAlert,
|
||||
RefreshCcw,
|
||||
RotateCcw,
|
||||
Pencil,
|
||||
@@ -72,6 +71,7 @@ import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/compon
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import ErrorBanner from "@/components/ui/ErrorBanner.vue";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
|
||||
import ImagePreviewDialog from "@/components/grid/ImagePreviewDialog.vue";
|
||||
@@ -181,7 +181,7 @@ const props = defineProps<{
|
||||
cacheKey?: string;
|
||||
onExecuteSql?: (sql: string) => Promise<void>;
|
||||
fullExportResult?: () => Promise<QueryResult | undefined>;
|
||||
customSave?: (changes: { dirtyRows: Map<number, Map<number, CellValue>>; newRows: CellValue[][]; deletedRows: Set<number>; columns: string[]; rows: CellValue[][] }) => Promise<void>;
|
||||
customSaveHandler?: import("@/composables/useDataGridEditor").CustomSaveHandler;
|
||||
}>();
|
||||
|
||||
const dataGridTraceId = uuid().slice(0, 8);
|
||||
@@ -1902,7 +1902,7 @@ const canShowWhereSearch = computed(() => !!props.onExecuteSql && !isResultsCont
|
||||
const canUseWhereSearch = computed(() => !!props.tableMeta && !!props.onExecuteSql && !isResultsContext.value);
|
||||
type DataGridTableMeta = NonNullable<typeof props.tableMeta>;
|
||||
const hiveTableTransactional = ref<boolean | undefined>(undefined);
|
||||
const canEditExistingRows = computed(() => !!props.customSave || canEditExistingTableRows(props.databaseType, hiveTableTransactional.value, props.tableMeta?.primaryKeys ?? []));
|
||||
const canEditExistingRows = computed(() => !!props.customSaveHandler || canEditExistingTableRows(props.databaseType, hiveTableTransactional.value, props.tableMeta?.primaryKeys ?? []));
|
||||
watch(
|
||||
() => [props.databaseType, props.connectionId, props.database, props.tableMeta?.schema, props.tableMeta?.tableName],
|
||||
async () => {
|
||||
@@ -2118,7 +2118,7 @@ const editor = useDataGridEditor({
|
||||
sourceColumns: computed(() => props.sourceColumns),
|
||||
canEditExistingRows,
|
||||
onExecuteSql: computed(() => props.onExecuteSql),
|
||||
customSave: computed(() => props.customSave),
|
||||
customSaveHandler: computed(() => props.customSaveHandler),
|
||||
sql: computed(() => props.sql),
|
||||
searchText,
|
||||
whereFilterInput,
|
||||
@@ -2234,7 +2234,7 @@ const saveActionMode = computed(() =>
|
||||
const saveToolbarState = computed(() =>
|
||||
dataGridSaveToolbarState({
|
||||
editable: props.editable,
|
||||
hasSaveTarget: !!props.tableMeta || !!props.customSave,
|
||||
hasSaveTarget: !!props.tableMeta || !!props.customSaveHandler,
|
||||
hasPendingChanges: hasPendingChanges.value,
|
||||
isSaving: isSaving.value,
|
||||
}),
|
||||
@@ -2242,13 +2242,13 @@ const saveToolbarState = computed(() =>
|
||||
const hasSearchBarSlot = computed(() => !!slots["search-bar"]);
|
||||
const showDataGridTopbar = computed(
|
||||
() =>
|
||||
(useTransaction.value && !!props.editable && (!!props.tableMeta || !!props.customSave)) ||
|
||||
(useTransaction.value && !!props.editable && (!!props.tableMeta || !!props.customSaveHandler)) ||
|
||||
hasLocalColumnFilters.value ||
|
||||
canShowWhereSearch.value ||
|
||||
hasSearchBarSlot.value ||
|
||||
showQueryEditReadyBadge.value ||
|
||||
props.context !== "results" ||
|
||||
(!!props.editable && (!!props.tableMeta || !!props.customSave)) ||
|
||||
(!!props.editable && (!!props.tableMeta || !!props.customSaveHandler)) ||
|
||||
transactionActive.value ||
|
||||
saveToolbarState.value.showActions,
|
||||
);
|
||||
@@ -2616,11 +2616,6 @@ const {
|
||||
isRowSelected,
|
||||
} = selection;
|
||||
|
||||
const selectionSummary = computed(() => {
|
||||
if (hasRowSelection.value) return t("grid.selectedRows", { count: selectedRowCount.value });
|
||||
return t("grid.selectedCells", { count: selectedCellCount.value });
|
||||
});
|
||||
|
||||
const multiRowCount = computed(() => {
|
||||
if (hasRowSelection.value) return selectedRowCount.value;
|
||||
const range = selectedRange.value;
|
||||
@@ -3734,9 +3729,11 @@ function canvasEditingCellViewportRect() {
|
||||
function canvasEditingCellIsVisible() {
|
||||
const rect = canvasEditingCellViewportRect();
|
||||
if (!rect) return false;
|
||||
const viewportWidth = canvasEffectiveViewportWidth();
|
||||
const viewportHeight = canvasEffectiveViewportHeight();
|
||||
const clippedLeft = Math.max(DATA_GRID_ROW_NUM_WIDTH, rect.left);
|
||||
const clippedRight = Math.min(canvasViewportWidth.value, rect.left + rect.width);
|
||||
return rect.top + rect.height > 0 && rect.top < canvasViewportHeight.value && clippedRight - clippedLeft > 0;
|
||||
const clippedRight = viewportWidth > 0 ? Math.min(viewportWidth, rect.left + rect.width) : rect.left + rect.width;
|
||||
return rect.top + rect.height > 0 && rect.top < viewportHeight && clippedRight - clippedLeft > 0;
|
||||
}
|
||||
|
||||
function commitHiddenCanvasEditBeforeCellInteraction() {
|
||||
@@ -3768,11 +3765,30 @@ const canvasSingleSelectedCell = computed(() => {
|
||||
return { rowIndex: range.startRow, visibleColIdx: range.startCol };
|
||||
});
|
||||
|
||||
function canvasEffectiveViewportWidth(): number {
|
||||
return canvasViewportWidth.value || canvasScrollerElement()?.clientWidth || 0;
|
||||
}
|
||||
|
||||
function canvasEffectiveViewportHeight(): number {
|
||||
return canvasViewportHeight.value || canvasScrollerElement()?.clientHeight || 0;
|
||||
}
|
||||
|
||||
const canvasOverlayStyle = computed(() => {
|
||||
const vw = canvasEffectiveViewportWidth();
|
||||
const vh = canvasEffectiveViewportHeight();
|
||||
return {
|
||||
width: `${vw}px`,
|
||||
height: `${vh}px`,
|
||||
marginTop: `-${vh}px`,
|
||||
};
|
||||
});
|
||||
|
||||
const canvasEditingCellStyle = computed(() => {
|
||||
const cell = canvasEditingCell.value;
|
||||
if (!cell) return {};
|
||||
const viewportWidth = canvasEffectiveViewportWidth();
|
||||
const clippedLeft = Math.max(DATA_GRID_ROW_NUM_WIDTH, cell.rect.left);
|
||||
const clippedRight = Math.min(canvasViewportWidth.value, cell.rect.left + cell.rect.width);
|
||||
const clippedRight = viewportWidth > 0 ? Math.min(viewportWidth, cell.rect.left + cell.rect.width) : cell.rect.left + cell.rect.width;
|
||||
return {
|
||||
left: `${clippedLeft}px`,
|
||||
top: `${cell.rect.top}px`,
|
||||
@@ -3789,11 +3805,13 @@ const canvasDetailButtonCell = computed(() => {
|
||||
if (visibleColIdx < 0) return null;
|
||||
const rect = canvasCellViewportRect(target.rowIndex, visibleColIdx);
|
||||
if (!rect) return null;
|
||||
const viewportWidth = canvasEffectiveViewportWidth();
|
||||
const viewportHeight = canvasEffectiveViewportHeight();
|
||||
const visibleLeft = Math.max(DATA_GRID_ROW_NUM_WIDTH, rect.left);
|
||||
const visibleRight = Math.min(canvasViewportWidth.value, rect.left + rect.width);
|
||||
const visibleRight = viewportWidth > 0 ? Math.min(viewportWidth, rect.left + rect.width) : rect.left + rect.width;
|
||||
const canQuickDownload = canQuickDownloadCellValue(target.rowIndex, target.col);
|
||||
const minWidth = canQuickDownload ? 46 : 24;
|
||||
if (rect.top < 0 || rect.top > canvasViewportHeight.value - 1 || visibleRight - visibleLeft < minWidth) return null;
|
||||
if (rect.top < 0 || rect.top > viewportHeight - 1 || visibleRight - visibleLeft < minWidth) return null;
|
||||
return { rowIndex: target.rowIndex, visibleColIdx, actualColIdx: target.col, rect, canQuickDownload };
|
||||
});
|
||||
|
||||
@@ -5858,7 +5876,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
"
|
||||
>
|
||||
<div class="data-grid-topbar flex items-stretch relative">
|
||||
<div v-if="useTransaction && editable && (tableMeta || customSave)" class="flex items-center px-2 py-0.5 border-r shrink-0">
|
||||
<div v-if="useTransaction && editable && (tableMeta || customSaveHandler)" class="flex items-center px-2 py-0.5 border-r shrink-0">
|
||||
<Select :model-value="rowStatusFilter" @update:model-value="(value: any) => setRowStatusFilter(String(value))">
|
||||
<SelectTrigger class="h-5 max-w-28 border-0 bg-transparent px-0 py-0 text-xs font-medium text-foreground/70 shadow-none focus-visible:ring-0 data-[state=open]:text-foreground [&_svg]:size-3">
|
||||
<SelectValue :placeholder="t('grid.filterRows')" />
|
||||
@@ -5883,7 +5901,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
</template>
|
||||
<template v-if="canShowWhereSearch">
|
||||
<div ref="searchSplitContainerRef" class="flex flex-1 min-w-0">
|
||||
<div class="flex flex-1 items-center gap-1 px-2 py-0.5 min-w-0 relative" :class="{ 'border-l': useTransaction && editable && (tableMeta || customSave) }" :style="whereSearchPaneStyle">
|
||||
<div class="flex flex-1 items-center gap-1 px-2 py-0.5 min-w-0 relative" :class="{ 'border-l': useTransaction && editable && (tableMeta || customSaveHandler) }" :style="whereSearchPaneStyle">
|
||||
<Popover v-model:open="filterBuilderOpen">
|
||||
<PopoverTrigger as-child>
|
||||
<button
|
||||
@@ -6147,7 +6165,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
{{ t("grid.renderModeHint") }}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Button v-if="editable && (tableMeta || customSave)" variant="ghost" size="sm" class="h-5 text-xs px-1.5 shrink-0" @click="addRow"> <Plus class="w-3 h-3 mr-1" /> {{ t("grid.addRow") }} </Button>
|
||||
<Button v-if="editable && (tableMeta || customSaveHandler)" variant="ghost" size="sm" class="h-5 text-xs px-1.5 shrink-0" @click="addRow"> <Plus class="w-3 h-3 mr-1" /> {{ t("grid.addRow") }} </Button>
|
||||
<template v-if="saveToolbarState.showActions">
|
||||
<Tooltip v-if="pendingChangeCount > 0">
|
||||
<TooltipTrigger as-child>
|
||||
@@ -6230,14 +6248,11 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
</button>
|
||||
</div>
|
||||
</Transition>
|
||||
<div v-if="isErrorResult" class="flex-1 flex flex-col items-center justify-center gap-2 px-6 text-center text-destructive">
|
||||
<TriangleAlert class="h-8 w-8 text-destructive/50" aria-hidden="true" />
|
||||
<div class="space-y-1">
|
||||
<div class="text-sm font-medium">{{ t("grid.queryError") }}</div>
|
||||
<div class="text-xs max-w-lg break-all text-destructive/80">{{ errorMessage }}</div>
|
||||
</div>
|
||||
<slot name="error-actions" :error-message="errorMessage" />
|
||||
</div>
|
||||
<ErrorBanner v-if="isErrorResult" variant="centered" :message="errorMessage">
|
||||
<template #actions>
|
||||
<slot name="error-actions" :error-message="errorMessage" />
|
||||
</template>
|
||||
</ErrorBanner>
|
||||
<div v-else-if="isTransposeMode" class="flex-1 flex flex-col min-h-0 overflow-hidden">
|
||||
<div class="h-8 flex items-center gap-2 px-3 border-y shrink-0 bg-muted/20">
|
||||
<Rows3 class="w-3.5 h-3.5 text-muted-foreground" />
|
||||
@@ -6708,15 +6723,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
@contextmenu="onCanvasContext"
|
||||
@dblclick="onCanvasDblClick"
|
||||
/>
|
||||
<div
|
||||
ref="canvasOverlayRef"
|
||||
class="canvas-grid-overlay sticky left-0 top-0 z-10 overflow-hidden"
|
||||
:style="{
|
||||
width: `${canvasViewportWidth}px`,
|
||||
height: `${canvasViewportHeight}px`,
|
||||
marginTop: `-${canvasViewportHeight}px`,
|
||||
}"
|
||||
>
|
||||
<div ref="canvasOverlayRef" class="canvas-grid-overlay sticky left-0 top-0 z-10 overflow-hidden" :style="canvasOverlayStyle">
|
||||
<div v-if="canvasEditingCell" class="absolute pointer-events-auto z-20" :class="{ 'tabular-nums': canvasEditingCellIsNumeric }" :style="canvasEditingCellStyle" @mousedown.stop @click.stop>
|
||||
<TemporalCellEditor v-if="temporalEditorKindForColumn(canvasEditingCell.actualColIdx)" v-model="editValue" :kind="temporalEditorKindForColumn(canvasEditingCell.actualColIdx)!" @cancel="cancelEdit" @commit="commitGridEdit" />
|
||||
<EnumCellEditor
|
||||
@@ -7264,11 +7271,8 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
<span v-if="showTruncationWarning" class="shrink-0 text-amber-500 text-xs">(truncated)</span>
|
||||
<span v-if="!hasData" class="shrink-0">{{ t("grid.rowsAffected", { count: result.affected_rows }) }}</span>
|
||||
<span class="shrink-0">{{ result.execution_time_ms }}ms</span>
|
||||
<span v-if="selectedRowCount > 0 || hasCellSelection" class="min-w-0 truncate text-foreground">
|
||||
{{ selectionSummary }}
|
||||
</span>
|
||||
|
||||
<template v-if="editable && (tableMeta || customSave)">
|
||||
<template v-if="editable && (tableMeta || customSaveHandler)">
|
||||
<span v-if="hasPendingChanges" class="shrink-0 text-foreground">
|
||||
{{ t("grid.pendingChanges", { count: pendingChangeCount }) }}
|
||||
</span>
|
||||
@@ -7753,7 +7757,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
.data-grid-horizontal-scrollbar {
|
||||
position: absolute;
|
||||
inset-inline: calc(var(--row-num-w) + 8px) 10px;
|
||||
bottom: 8px;
|
||||
bottom: 2px;
|
||||
z-index: 30;
|
||||
height: 10px;
|
||||
cursor: pointer;
|
||||
@@ -7767,7 +7771,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
top: 4px;
|
||||
height: 2px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in oklch, var(--foreground) 12%, transparent);
|
||||
background: color-mix(in oklch, var(--foreground) 7%, transparent);
|
||||
}
|
||||
|
||||
.data-grid-horizontal-scrollbar__thumb {
|
||||
@@ -7776,7 +7780,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
height: 4px;
|
||||
min-width: 24px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in oklch, var(--foreground) 42%, transparent);
|
||||
background: color-mix(in oklch, var(--foreground) 24%, transparent);
|
||||
transition:
|
||||
height 120ms ease,
|
||||
background-color 120ms ease,
|
||||
@@ -7787,7 +7791,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
.data-grid-horizontal-scrollbar--dragging .data-grid-horizontal-scrollbar__thumb {
|
||||
top: 2px;
|
||||
height: 6px;
|
||||
background: color-mix(in oklch, var(--foreground) 62%, transparent);
|
||||
background: color-mix(in oklch, var(--foreground) 42%, transparent);
|
||||
}
|
||||
|
||||
.canvas-grid-surface {
|
||||
|
||||
@@ -30,6 +30,7 @@ const emit = defineEmits<{
|
||||
const open = ref(true);
|
||||
const triggerRef = ref<HTMLButtonElement | null>(null);
|
||||
let closeHandled = false;
|
||||
let isCommitting = false;
|
||||
|
||||
const hasDate = computed(() => props.kind !== "time");
|
||||
const hasTime = computed(() => props.kind !== "date");
|
||||
@@ -136,12 +137,16 @@ function setNow() {
|
||||
}
|
||||
|
||||
function finishCommit() {
|
||||
if (isCommitting) return;
|
||||
closeHandled = true;
|
||||
isCommitting = true;
|
||||
emit("commit");
|
||||
}
|
||||
|
||||
function finishCancel() {
|
||||
if (isCommitting) return;
|
||||
closeHandled = true;
|
||||
isCommitting = true;
|
||||
emit("cancel");
|
||||
}
|
||||
|
||||
@@ -200,7 +205,7 @@ function twoDigit(value: string | number): string {
|
||||
<PopoverContent align="start" side="bottom" class="w-auto gap-1.5 rounded-md p-1.5" @click.stop @keydown.stop="onKeydown" @interact-outside="onPopoverInteractOutside">
|
||||
<div v-if="hasDate" class="grid grid-cols-[4.5rem_4.5rem_4.5rem] gap-1.5">
|
||||
<div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
|
||||
<input :value="dateParts.year" data-temporal-part="year" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateDateFromInput('year', $event)" />
|
||||
<input :value="dateParts.year" data-temporal-part="year" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @input="updateDateFromInput('year', $event)" />
|
||||
<div class="grid border-l">
|
||||
<button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepDate('year', 1)">
|
||||
<ChevronUp class="h-3 w-3" />
|
||||
@@ -212,7 +217,7 @@ function twoDigit(value: string | number): string {
|
||||
</div>
|
||||
|
||||
<div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
|
||||
<input :value="twoDigit(dateParts.month)" data-temporal-part="month" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateDateFromInput('month', $event)" />
|
||||
<input :value="twoDigit(dateParts.month)" data-temporal-part="month" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @input="updateDateFromInput('month', $event)" />
|
||||
<div class="grid border-l">
|
||||
<button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepDate('month', 1)">
|
||||
<ChevronUp class="h-3 w-3" />
|
||||
@@ -224,7 +229,7 @@ function twoDigit(value: string | number): string {
|
||||
</div>
|
||||
|
||||
<div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
|
||||
<input :value="twoDigit(dateParts.day)" data-temporal-part="day" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateDateFromInput('day', $event)" />
|
||||
<input :value="twoDigit(dateParts.day)" data-temporal-part="day" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @input="updateDateFromInput('day', $event)" />
|
||||
<div class="grid border-l">
|
||||
<button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepDate('day', 1)">
|
||||
<ChevronUp class="h-3 w-3" />
|
||||
@@ -238,7 +243,7 @@ function twoDigit(value: string | number): string {
|
||||
|
||||
<div v-if="hasTime" class="grid grid-cols-[3.5rem_0.5rem_3.5rem_0.5rem_3.5rem] items-center gap-1.5">
|
||||
<div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
|
||||
<input :value="twoDigit(timeParts.hour)" data-temporal-part="hour" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateTimeFromInput('hour', $event)" />
|
||||
<input :value="twoDigit(timeParts.hour)" data-temporal-part="hour" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @input="updateTimeFromInput('hour', $event)" />
|
||||
<div class="grid border-l">
|
||||
<button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepTime('hour', 1)">
|
||||
<ChevronUp class="h-3 w-3" />
|
||||
@@ -250,7 +255,7 @@ function twoDigit(value: string | number): string {
|
||||
</div>
|
||||
<span class="text-center text-xs text-muted-foreground">:</span>
|
||||
<div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
|
||||
<input :value="twoDigit(timeParts.minute)" data-temporal-part="minute" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateTimeFromInput('minute', $event)" />
|
||||
<input :value="twoDigit(timeParts.minute)" data-temporal-part="minute" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @input="updateTimeFromInput('minute', $event)" />
|
||||
<div class="grid border-l">
|
||||
<button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepTime('minute', 1)">
|
||||
<ChevronUp class="h-3 w-3" />
|
||||
@@ -262,7 +267,7 @@ function twoDigit(value: string | number): string {
|
||||
</div>
|
||||
<span class="text-center text-xs text-muted-foreground">:</span>
|
||||
<div class="grid h-7 min-w-0 grid-cols-[1fr_1.35rem] overflow-hidden rounded-md border border-input bg-background">
|
||||
<input :value="twoDigit(timeParts.second)" data-temporal-part="second" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @change="updateTimeFromInput('second', $event)" />
|
||||
<input :value="twoDigit(timeParts.second)" data-temporal-part="second" inputmode="numeric" class="min-w-0 bg-transparent px-1 text-center text-[13px] tabular-nums outline-none" @input="updateTimeFromInput('second', $event)" />
|
||||
<div class="grid border-l">
|
||||
<button type="button" class="flex items-center justify-center hover:bg-muted" @click="stepTime('second', 1)">
|
||||
<ChevronUp class="h-3 w-3" />
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
import { computed, ref, watch, nextTick } from "vue";
|
||||
import type { CSSProperties } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { X, Pin, ChevronDown, Table2, Code2, TableProperties, PencilRuler, KeyRound, Pencil, Package, Check, Lock, Copy } from "@lucide/vue";
|
||||
import { X, Pin, ChevronDown, Table2, Code2, TableProperties, PencilRuler, KeyRound, Pencil, Package, Check, Lock, Copy, AlertTriangle } from "@lucide/vue";
|
||||
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
|
||||
import LightDropdown from "@/components/ui/LightDropdown.vue";
|
||||
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useQueryStore } from "@/stores/queryStore";
|
||||
import { useSettingsStore } from "@/stores/settingsStore";
|
||||
import { useTabScroll } from "@/composables/useTabScroll";
|
||||
@@ -22,6 +24,7 @@ const props = defineProps<{
|
||||
const emit = defineEmits<{
|
||||
"toggle-driver-store": [];
|
||||
"close-driver-store": [];
|
||||
"save-tab": [tabId: string];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -113,6 +116,19 @@ function getTabMenuItems(tab: QueryTab): ContextMenuItem[] {
|
||||
];
|
||||
}
|
||||
|
||||
function handleSaveAndClose() {
|
||||
const id = queryStore.saveAndClosePendingTab();
|
||||
if (id) emit("save-tab", id);
|
||||
}
|
||||
|
||||
function handleDiscardAndClose() {
|
||||
queryStore.forceClosePendingTab();
|
||||
}
|
||||
|
||||
function handleCancelClose() {
|
||||
queryStore.cancelClosePendingTab();
|
||||
}
|
||||
|
||||
const tabsContainerRef = ref<HTMLElement | null>(null);
|
||||
const { hasTabOverflow, scrollThumbLeftPercent, scrollThumbWidthPercent, isScrollbarDragging, updateScrollButtons, onTabsWheel, startScrollbarDrag } = useTabScroll(tabsContainerRef);
|
||||
const tabScrollBehavior = ref<ScrollBehavior>("smooth");
|
||||
@@ -267,7 +283,7 @@ function activateTab(tabId: string) {
|
||||
|
||||
<template>
|
||||
<div v-if="queryStore.tabs.length > 0 || showDriverStore" class="relative flex border-b shrink-0" :class="settingsStore.editorSettings.appLayout === 'classic' ? 'h-9 items-stretch bg-muted' : 'h-10 items-center bg-background px-2'">
|
||||
<div class="relative h-full min-w-0 flex-1">
|
||||
<div class="app-tab-strip relative h-full min-w-0 flex-1">
|
||||
<div v-if="showTabOverflowControls" class="app-tab-scrollbar" :class="{ 'app-tab-scrollbar--dragging': isScrollbarDragging }" @pointerdown="startScrollbarDrag">
|
||||
<div class="app-tab-scrollbar__thumb" :style="tabScrollbarThumbStyle" />
|
||||
</div>
|
||||
@@ -387,6 +403,30 @@ function activateTab(tabId: string) {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Dialog
|
||||
:open="queryStore.showCloseConfirm"
|
||||
@update:open="
|
||||
(open) => {
|
||||
if (!open) queryStore.cancelClosePendingTab();
|
||||
}
|
||||
"
|
||||
>
|
||||
<DialogContent class="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="flex items-center gap-2">
|
||||
<AlertTriangle class="h-5 w-5 text-amber-500" />
|
||||
{{ t("editor.unsavedChangesTitle") }}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p class="text-sm text-muted-foreground">{{ t("editor.unsavedChangesMessage") }}</p>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="handleCancelClose">{{ t("common.cancel") }}</Button>
|
||||
<Button variant="secondary" @click="handleDiscardAndClose">{{ t("editor.discardChanges") }}</Button>
|
||||
<Button @click="handleSaveAndClose">{{ t("savedSql.save") }}</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
@@ -401,7 +441,17 @@ function activateTab(tabId: string) {
|
||||
z-index: 20;
|
||||
height: 6px;
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
touch-action: none;
|
||||
transition: opacity 140ms ease;
|
||||
}
|
||||
|
||||
.app-tab-strip:hover .app-tab-scrollbar,
|
||||
.app-tab-strip:focus-within .app-tab-scrollbar,
|
||||
.app-tab-scrollbar--dragging {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.app-tab-scrollbar::before {
|
||||
|
||||
@@ -33,7 +33,7 @@ function preloadDataGridComponent() {
|
||||
const DataGrid = defineAsyncComponent(loadDataGridComponent);
|
||||
const RedisKeyBrowser = defineAsyncComponent(() => import("@/components/redis/RedisKeyBrowser.vue"));
|
||||
const EtcdKeyBrowser = defineAsyncComponent(() => import("@/components/etcd/EtcdKeyBrowser.vue"));
|
||||
const MongoDocBrowser = defineAsyncComponent(() => import("@/components/mongo/MongoDocBrowser.vue"));
|
||||
const DocumentBrowser = defineAsyncComponent(() => import("@/components/document/DocumentBrowser.vue"));
|
||||
const ObjectBrowser = defineAsyncComponent(() => import("@/components/objects/ObjectBrowser.vue"));
|
||||
const TableStructureEditor = defineAsyncComponent(() => import("@/components/structure/TableStructureEditor.vue"));
|
||||
const DatabaseUserAdmin = defineAsyncComponent(() => import("@/components/admin/DatabaseUserAdmin.vue"));
|
||||
@@ -823,7 +823,7 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });
|
||||
<!-- Document mode: MongoDB collections and Elasticsearch indices -->
|
||||
<template v-else-if="activeTab.mode === 'mongo'">
|
||||
<div class="flex-1 min-h-0">
|
||||
<MongoDocBrowser :key="activeTab.id" :connection-id="activeTab.connectionId" :database="activeTab.database" :collection="activeTab.sql" :database-type="activeEffectiveDatabaseType" />
|
||||
<DocumentBrowser :key="activeTab.id" :connection-id="activeTab.connectionId" :database="activeTab.database" :collection="activeTab.sql" :database-type="activeEffectiveDatabaseType" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, watchEffect } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { Play, Loader2, Square, Database, Check, Table2, AlignLeft, GitBranch, Save, FolderOpen, Layers, X } from "@lucide/vue";
|
||||
import { Play, Loader2, Square, Database, Check, Table2, AlignLeft, GitBranch, Save, FolderOpen, Layers, X, Shield } from "@lucide/vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { SearchableSelect } from "@/components/ui/searchable-select";
|
||||
@@ -23,6 +23,7 @@ const props = defineProps<{
|
||||
activeConnection?: ConnectionConfig;
|
||||
executableSql: string;
|
||||
explainMode?: string;
|
||||
blockDangerousRedisCommands?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -38,6 +39,7 @@ const emit = defineEmits<{
|
||||
changeSchema: [schema: string | undefined];
|
||||
setDefaultDatabase: [];
|
||||
clearDefaultDatabase: [];
|
||||
"update:blockDangerousRedisCommands": [value: boolean];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -54,6 +56,10 @@ const connectionOptionIds = computed(() => connectionStore.connections.map((conn
|
||||
const activeDatabaseValue = computed(() => props.activeTab.database || "");
|
||||
const activeConnectionValue = computed(() => props.activeConnection?.id || "");
|
||||
const activeSchemaValue = computed(() => props.activeTab.schema || "");
|
||||
const supportsExplain = computed(() => {
|
||||
const dbType = props.activeConnection?.db_type;
|
||||
return dbType !== "redis" && dbType !== "mongodb" && dbType !== "elasticsearch" && dbType !== "etcd";
|
||||
});
|
||||
const isSingleDb = computed(() => isSingleDatabase(props.activeConnection?.db_type));
|
||||
const hasDefaultDatabaseOption = computed(() => activeDatabaseOptions.value.includes(""));
|
||||
const schemaDatabaseKey = computed(() => props.activeTab.database || (isSingleDb.value ? "_" : ""));
|
||||
@@ -119,7 +125,7 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ activeTab.isExecuting ? t("toolbar.stopQuery") : t("toolbar.executeShortcut") }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<Tooltip v-if="supportsExplain">
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
:variant="activeTab.isExplaining ? 'destructive' : 'ghost'"
|
||||
@@ -155,6 +161,20 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ t("toolbar.formatSql") }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip v-if="activeConnection?.db_type === 'redis'">
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="h-6 w-6"
|
||||
:class="blockDangerousRedisCommands !== false ? 'text-orange-600 bg-orange-100 dark:text-orange-300 dark:bg-orange-900/30' : 'text-muted-foreground/50'"
|
||||
@click="emit('update:blockDangerousRedisCommands', blockDangerousRedisCommands === false)"
|
||||
>
|
||||
<Shield class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ t("toolbar.blockDangerousRedisCommands") }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon" class="h-6 w-6 text-blue-600 hover:bg-blue-500/10 hover:text-blue-700 dark:text-blue-300 dark:hover:text-blue-200" :disabled="!activeTab.sql.trim()" @click="emit('saveSql')">
|
||||
|
||||
@@ -147,19 +147,25 @@ async function exportFolderContents(folder?: SavedSqlFolder) {
|
||||
const rootDir = await join(targetDir, rootDirName);
|
||||
await mkdir(rootDir, { recursive: true });
|
||||
|
||||
if (folder) {
|
||||
for (const file of savedSqlStore.filesInFolder(folder.id)) {
|
||||
const filePath = await join(rootDir, sanitizeFileSystemSegment(ensureSqlExtension(file.name)));
|
||||
const writeFolder = async (libraryFolder: SavedSqlFolder, dir: string): Promise<void> => {
|
||||
for (const child of savedSqlStore.allFolders.filter((item) => item.parentFolderId === libraryFolder.id)) {
|
||||
const childDir = await join(dir, sanitizeFileSystemSegment(child.name));
|
||||
await mkdir(childDir, { recursive: true });
|
||||
await writeFolder(child, childDir);
|
||||
}
|
||||
for (const file of savedSqlStore.filesInFolder(libraryFolder.id)) {
|
||||
const filePath = await join(dir, sanitizeFileSystemSegment(ensureSqlExtension(file.name)));
|
||||
await writeTextFile(filePath, file.sql);
|
||||
}
|
||||
};
|
||||
|
||||
if (folder) {
|
||||
await writeFolder(folder, rootDir);
|
||||
} else {
|
||||
for (const libraryFolder of savedSqlStore.allFolders.filter((item) => isConnectionVisible(item.connectionId))) {
|
||||
for (const libraryFolder of savedSqlStore.allFolders.filter((item) => isConnectionVisible(item.connectionId) && !item.parentFolderId)) {
|
||||
const folderDir = await join(rootDir, sanitizeFileSystemSegment(libraryFolder.name));
|
||||
await mkdir(folderDir, { recursive: true });
|
||||
for (const file of savedSqlStore.filesInFolder(libraryFolder.id)) {
|
||||
const filePath = await join(folderDir, sanitizeFileSystemSegment(ensureSqlExtension(file.name)));
|
||||
await writeTextFile(filePath, file.sql);
|
||||
}
|
||||
await writeFolder(libraryFolder, folderDir);
|
||||
}
|
||||
|
||||
const unfiled = savedSqlStore.filesWithoutFolder().filter((file) => !orphanedIds.value.has(file.id));
|
||||
@@ -310,6 +316,20 @@ function folderMatchesQuery(folder: SavedSqlFolder) {
|
||||
return savedSqlStore.filesInFolder(folder.id).some((file) => !orphanedIds.value.has(file.id) && fileMatchesQuery(file));
|
||||
}
|
||||
|
||||
function childFolders(parentFolderId?: string) {
|
||||
return savedSqlStore.allFolders.filter((folder) => isConnectionVisible(folder.connectionId) && (folder.parentFolderId || "") === (parentFolderId || ""));
|
||||
}
|
||||
|
||||
function descendantFolders(parentFolderId: string): SavedSqlFolder[] {
|
||||
const direct = childFolders(parentFolderId);
|
||||
return direct.flatMap((folder) => [folder, ...descendantFolders(folder.id)]);
|
||||
}
|
||||
|
||||
function folderBranchMatchesQuery(folder: SavedSqlFolder) {
|
||||
if (folderMatchesQuery(folder)) return true;
|
||||
return descendantFolders(folder.id).some((child) => folderMatchesQuery(child));
|
||||
}
|
||||
|
||||
function filesInFolder(folderId: string) {
|
||||
const folder = savedSqlStore.allFolders.find((item) => item.id === folderId);
|
||||
const includeAllFilesForMatchedFolder = !!folder && !!searchQuery.value && folder.name.toLowerCase().includes(searchQuery.value);
|
||||
@@ -319,7 +339,26 @@ function filesInFolder(folderId: string) {
|
||||
.filter((file) => includeAllFilesForMatchedFolder || fileMatchesQuery(file));
|
||||
}
|
||||
|
||||
const visibleFolders = computed(() => savedSqlStore.allFolders.filter((folder) => isConnectionVisible(folder.connectionId) && folderMatchesQuery(folder)));
|
||||
type SqlLibraryRow = { type: "folder"; folder: SavedSqlFolder; depth: number } | { type: "file"; file: SavedSqlFile; depth: number };
|
||||
|
||||
const visibleFolderRows = computed<SqlLibraryRow[]>(() => {
|
||||
const rows: SqlLibraryRow[] = [];
|
||||
const appendFolder = (folder: SavedSqlFolder, depth: number) => {
|
||||
if (!folderBranchMatchesQuery(folder)) return;
|
||||
rows.push({ type: "folder", folder, depth });
|
||||
if (!isFolderExpanded(folder.id)) return;
|
||||
for (const child of childFolders(folder.id)) {
|
||||
appendFolder(child, depth + 1);
|
||||
}
|
||||
for (const file of filesInFolder(folder.id)) {
|
||||
rows.push({ type: "file", file, depth: depth + 1 });
|
||||
}
|
||||
};
|
||||
for (const folder of childFolders()) {
|
||||
appendFolder(folder, 0);
|
||||
}
|
||||
return rows;
|
||||
});
|
||||
|
||||
const visibleFiles = computed(() =>
|
||||
savedSqlStore
|
||||
@@ -328,7 +367,7 @@ const visibleFiles = computed(() =>
|
||||
.filter((file) => fileMatchesQuery(file)),
|
||||
);
|
||||
|
||||
const hasAnyVisibleItem = computed(() => visibleFolders.value.length > 0 || visibleFiles.value.length > 0);
|
||||
const hasAnyVisibleItem = computed(() => visibleFolderRows.value.length > 0 || visibleFiles.value.length > 0);
|
||||
|
||||
const collapsedFolders = ref<Set<string>>(new Set());
|
||||
|
||||
@@ -344,31 +383,15 @@ function isFolderExpanded(folderId: string) {
|
||||
return !collapsedFolders.value.has(folderId);
|
||||
}
|
||||
|
||||
const showNewFolderInput = ref(false);
|
||||
const newFolderName = ref("");
|
||||
const newFolderInputRef = ref<HTMLInputElement | null>(null);
|
||||
|
||||
function openNewFolderInput() {
|
||||
newFolderName.value = "";
|
||||
showNewFolderInput.value = true;
|
||||
nextTick(() => newFolderInputRef.value?.focus());
|
||||
}
|
||||
|
||||
async function confirmNewFolder() {
|
||||
const name = newFolderName.value.trim();
|
||||
if (!name) {
|
||||
cancelNewFolder();
|
||||
return;
|
||||
}
|
||||
showNewFolderInput.value = false;
|
||||
const connectionId = connectionStore.connections[0]?.id;
|
||||
async function openNewFolderInput(parentFolderId?: string) {
|
||||
const parent = parentFolderId ? savedSqlStore.allFolders.find((folder) => folder.id === parentFolderId) : undefined;
|
||||
const connectionId = parent?.connectionId || connectionStore.connections[0]?.id;
|
||||
if (!connectionId) return;
|
||||
await savedSqlStore.createFolder(connectionId, name);
|
||||
}
|
||||
|
||||
function cancelNewFolder() {
|
||||
showNewFolderInput.value = false;
|
||||
newFolderName.value = "";
|
||||
if (parent?.id) {
|
||||
collapsedFolders.value = new Set([...collapsedFolders.value].filter((id) => id !== parent.id));
|
||||
}
|
||||
const folder = await savedSqlStore.createFolder(connectionId, t("savedSql.newFolderDefault"), parent?.id);
|
||||
startRenameFolder(folder);
|
||||
}
|
||||
|
||||
const renamingTarget = ref<{ type: "folder" | "file"; id: string } | null>(null);
|
||||
@@ -479,6 +502,7 @@ const contextMenuItems = computed<CtxMenuItem[]>(() => {
|
||||
];
|
||||
}
|
||||
return [
|
||||
{ label: t("savedSql.newFolder"), action: () => openNewFolderInput(target.id), icon: FolderPlus },
|
||||
{ label: t("sqlLibrary.importIntoFolder"), action: () => importDirectoryIntoLibrary(target), icon: Upload },
|
||||
{ label: t("sqlLibrary.exportFolder"), action: () => exportFolderContents(target), icon: Download },
|
||||
{ label: "", separator: true },
|
||||
@@ -619,6 +643,11 @@ async function performDrop() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (draggedType === "folder" && targetType === "folder" && dropPosition === "inside") {
|
||||
await savedSqlStore.moveFolderToFolder(draggedId, targetId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (draggedType !== "file") return;
|
||||
|
||||
if (targetType === "folder") {
|
||||
@@ -677,7 +706,9 @@ function updateDropTarget(event: MouseEvent, targetId: string, targetType: DragI
|
||||
let nextPosition: DropPosition | null = null;
|
||||
if (dragState.draggedType === "folder" && targetType === "folder") {
|
||||
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
|
||||
nextPosition = event.clientY - rect.top < rect.height / 2 ? "before" : "after";
|
||||
const y = event.clientY - rect.top;
|
||||
const third = rect.height / 3;
|
||||
nextPosition = y > third && y < rect.height - third ? "inside" : y < rect.height / 2 ? "before" : "after";
|
||||
} else if (dragState.draggedType === "file" && targetType === "file") {
|
||||
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
|
||||
nextPosition = event.clientY - rect.top < rect.height / 2 ? "before" : "after";
|
||||
@@ -744,19 +775,6 @@ function showDropInside(targetId: string) {
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-1">
|
||||
<div v-if="showNewFolderInput" class="flex items-center gap-1 px-2 py-1.5">
|
||||
<FolderOpen class="h-4 w-4 text-amber-500 shrink-0" />
|
||||
<input
|
||||
ref="newFolderInputRef"
|
||||
v-model="newFolderName"
|
||||
class="h-6 min-w-0 flex-1 rounded border border-border bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
:placeholder="t('savedSql.newFolderDefault')"
|
||||
@keydown.enter.prevent="confirmNewFolder"
|
||||
@keydown.escape.prevent="cancelNewFolder"
|
||||
@blur="confirmNewFolder"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<CustomContextMenu :items="contextMenuItems" @close="clearContextTarget">
|
||||
<template #default="{ onContextMenu }">
|
||||
<div
|
||||
@@ -766,23 +784,25 @@ function showDropInside(targetId: string) {
|
||||
onContextMenu($event);
|
||||
"
|
||||
>
|
||||
<div v-for="folder in visibleFolders" :key="folder.id" class="mb-0.5">
|
||||
<div v-for="row in visibleFolderRows" :key="row.type === 'folder' ? row.folder.id : row.file.id" class="mb-0.5">
|
||||
<div
|
||||
class="relative flex items-center gap-1 rounded px-2 py-1.5 text-xs cursor-pointer transition-colors group"
|
||||
:class="[showDropInside(folder.id) ? 'ring-1 ring-primary/50 bg-primary/5' : 'hover:bg-accent', isDraggingItem(folder.id) ? 'opacity-50' : '']"
|
||||
@mousedown="handleDragMouseDown($event, folder.id, 'folder')"
|
||||
@mousemove="updateDropTarget($event, folder.id, 'folder')"
|
||||
@mouseleave="clearDropTarget(folder.id)"
|
||||
@click="toggleFolder(folder.id)"
|
||||
v-if="row.type === 'folder'"
|
||||
class="relative flex items-center gap-1 rounded py-1.5 pr-2 text-xs cursor-pointer transition-colors group"
|
||||
:style="{ paddingLeft: `${8 + row.depth * 16}px` }"
|
||||
:class="[showDropInside(row.folder.id) ? 'ring-1 ring-primary/50 bg-primary/5' : 'hover:bg-accent', isDraggingItem(row.folder.id) ? 'opacity-50' : '']"
|
||||
@mousedown="handleDragMouseDown($event, row.folder.id, 'folder')"
|
||||
@mousemove="updateDropTarget($event, row.folder.id, 'folder')"
|
||||
@mouseleave="clearDropTarget(row.folder.id)"
|
||||
@click="toggleFolder(row.folder.id)"
|
||||
@contextmenu.prevent="
|
||||
contextTarget = folder;
|
||||
contextTarget = row.folder;
|
||||
onContextMenu($event);
|
||||
"
|
||||
>
|
||||
<div v-if="showDropBefore(folder.id)" class="absolute left-2 right-2 top-0 border-t-2 border-primary" />
|
||||
<div v-if="showDropAfter(folder.id)" class="absolute left-2 right-2 bottom-0 border-b-2 border-primary" />
|
||||
<component :is="isFolderExpanded(folder.id) ? FolderOpen : FolderClosed" class="h-4 w-4 text-amber-500 shrink-0" />
|
||||
<template v-if="renamingTarget?.type === 'folder' && renamingTarget.id === folder.id">
|
||||
<div v-if="showDropBefore(row.folder.id)" class="absolute left-2 right-2 top-0 border-t-2 border-primary" />
|
||||
<div v-if="showDropAfter(row.folder.id)" class="absolute left-2 right-2 bottom-0 border-b-2 border-primary" />
|
||||
<component :is="isFolderExpanded(row.folder.id) ? FolderOpen : FolderClosed" class="h-4 w-4 text-amber-500 shrink-0" />
|
||||
<template v-if="renamingTarget?.type === 'folder' && renamingTarget.id === row.folder.id">
|
||||
<input
|
||||
:ref="setRenameInputRef"
|
||||
v-model="renameValue"
|
||||
@@ -795,48 +815,42 @@ function showDropInside(targetId: string) {
|
||||
/>
|
||||
</template>
|
||||
<span v-else class="dbx-sql-library-drag-label min-w-0 flex-1 truncate">
|
||||
{{ folder.name }}
|
||||
<span class="ml-1 text-muted-foreground">({{ filesInFolder(folder.id).length }})</span>
|
||||
{{ row.folder.name }}
|
||||
<span class="ml-1 text-muted-foreground">({{ filesInFolder(row.folder.id).length }})</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="isFolderExpanded(folder.id)" class="ml-4">
|
||||
<div
|
||||
v-for="file in filesInFolder(folder.id)"
|
||||
:key="file.id"
|
||||
class="relative flex items-center gap-1 rounded px-2 py-1.5 text-xs cursor-pointer transition-colors group"
|
||||
:class="[isDraggingItem(file.id) ? 'opacity-50' : 'hover:bg-accent']"
|
||||
@mousedown="handleDragMouseDown($event, file.id, 'file')"
|
||||
@mousemove="updateDropTarget($event, file.id, 'file')"
|
||||
@mouseleave="clearDropTarget(file.id)"
|
||||
@click="openFile(file)"
|
||||
@contextmenu.prevent="
|
||||
contextTarget = file;
|
||||
onContextMenu($event);
|
||||
"
|
||||
>
|
||||
<div v-if="showDropBefore(file.id)" class="absolute left-2 right-2 top-0 border-t-2 border-primary" />
|
||||
<div v-if="showDropAfter(file.id)" class="absolute left-2 right-2 bottom-0 border-b-2 border-primary" />
|
||||
<FileText class="h-3.5 w-3.5 text-blue-400 shrink-0" />
|
||||
<template v-if="renamingTarget?.type === 'file' && renamingTarget.id === file.id">
|
||||
<input
|
||||
:ref="setRenameInputRef"
|
||||
v-model="renameValue"
|
||||
data-no-drag="true"
|
||||
class="min-w-0 flex-1 rounded border border-primary/50 bg-transparent px-1 text-xs outline-none"
|
||||
@keydown.enter.prevent="confirmRename"
|
||||
@keydown.escape.prevent="cancelRename"
|
||||
@blur="confirmRename"
|
||||
@click.stop
|
||||
/>
|
||||
</template>
|
||||
<span v-else class="dbx-sql-library-drag-label min-w-0 flex-1 truncate">{{ file.name }}</span>
|
||||
<span class="shrink-0 text-xs text-muted-foreground"> [{{ getConnectionLabel(file.connectionId) }}] </span>
|
||||
</div>
|
||||
|
||||
<div v-if="filesInFolder(folder.id).length === 0" class="px-2 py-1 text-xs text-muted-foreground">
|
||||
{{ t("sqlLibrary.emptyFolder") }}
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="relative flex items-center gap-1 rounded py-1.5 pr-2 text-xs cursor-pointer transition-colors group"
|
||||
:style="{ paddingLeft: `${8 + row.depth * 16}px` }"
|
||||
:class="[isDraggingItem(row.file.id) ? 'opacity-50' : 'hover:bg-accent']"
|
||||
@mousedown="handleDragMouseDown($event, row.file.id, 'file')"
|
||||
@mousemove="updateDropTarget($event, row.file.id, 'file')"
|
||||
@mouseleave="clearDropTarget(row.file.id)"
|
||||
@click="openFile(row.file)"
|
||||
@contextmenu.prevent="
|
||||
contextTarget = row.file;
|
||||
onContextMenu($event);
|
||||
"
|
||||
>
|
||||
<div v-if="showDropBefore(row.file.id)" class="absolute left-2 right-2 top-0 border-t-2 border-primary" />
|
||||
<div v-if="showDropAfter(row.file.id)" class="absolute left-2 right-2 bottom-0 border-b-2 border-primary" />
|
||||
<FileText class="h-3.5 w-3.5 text-blue-400 shrink-0" />
|
||||
<template v-if="renamingTarget?.type === 'file' && renamingTarget.id === row.file.id">
|
||||
<input
|
||||
:ref="setRenameInputRef"
|
||||
v-model="renameValue"
|
||||
data-no-drag="true"
|
||||
class="min-w-0 flex-1 rounded border border-primary/50 bg-transparent px-1 text-xs outline-none"
|
||||
@keydown.enter.prevent="confirmRename"
|
||||
@keydown.escape.prevent="cancelRename"
|
||||
@blur="confirmRename"
|
||||
@click.stop
|
||||
/>
|
||||
</template>
|
||||
<span v-else class="dbx-sql-library-drag-label min-w-0 flex-1 truncate">{{ row.file.name }}</span>
|
||||
<span class="shrink-0 text-xs text-muted-foreground"> [{{ getConnectionLabel(row.file.connectionId) }}] </span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -883,7 +897,7 @@ function showDropInside(targetId: string) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!hasAnyVisibleItem && !showNewFolderInput" class="flex h-full flex-col items-center justify-center gap-2 text-muted-foreground">
|
||||
<div v-if="!hasAnyVisibleItem" class="flex h-full flex-col items-center justify-center gap-2 text-muted-foreground">
|
||||
<Library class="h-8 w-8 opacity-30" />
|
||||
<p class="text-xs">{{ t("sqlLibrary.empty") }}</p>
|
||||
</div>
|
||||
|
||||
@@ -63,7 +63,7 @@ import { resolveDefaultDatabase } from "@/lib/defaultDatabase";
|
||||
import { canTreeNodeShowExpander, treeItemPaddingLeft, usesFullWidthTreeLabel } from "@/lib/sidebarTreeItemLayout";
|
||||
import { buildTableSelectSql } from "@/lib/tableSelectSql";
|
||||
import { clearActiveTableReferencePayload, createTableReferencePayload, createTableReferenceDropEvent, setActiveTableReferencePayload, type QueryEditorTableReferencePayload } from "@/lib/queryEditorTableDrop";
|
||||
import { editablePrimaryKeys } from "@/lib/tableEditing";
|
||||
import { editablePrimaryKeys, usesSyntheticRowIdKey } from "@/lib/tableEditing";
|
||||
import { supportsDatabaseCreation, supportsDatabaseSearch, supportsFieldLineage, supportsObjectBrowserTreeNode, supportsSchemaDiagram, supportsSqlFileExecution, supportsTableImport, supportsTableTruncate, supportsTableStructureEditing, usesTreeSchemaMode } from "@/lib/databaseCapabilities";
|
||||
import { copyNameForTreeNode, objectSourceKindForTreeNode, sidebarSelectionCopyAction, treeNodeRowAction, treeNodeRowDoubleClickAction } from "@/lib/treeNodeClick";
|
||||
import { formatSqlInsert } from "@/lib/exportFormats";
|
||||
@@ -700,56 +700,58 @@ async function openData() {
|
||||
const querySchema = connectionObjectTreeQuerySchema(config, node.database, tableSchema);
|
||||
const effectiveDbType = effectiveDatabaseTypeForConnection(config);
|
||||
const limit = settingsStore.editorSettings.pageSize;
|
||||
let columns: ColumnInfo[] = [];
|
||||
let primaryKeys: string[] = [];
|
||||
try {
|
||||
console.info("[DBX][openData:get-columns:start]", {
|
||||
traceId,
|
||||
database: node.database,
|
||||
schema: querySchema,
|
||||
table: node.label,
|
||||
elapsed: elapsed(),
|
||||
});
|
||||
columns = await api.getColumns(node.connectionId, node.database, querySchema, node.label);
|
||||
primaryKeys = editablePrimaryKeys(effectiveDbType, columns);
|
||||
console.info("[DBX][openData:get-columns:done]", {
|
||||
traceId,
|
||||
columnCount: columns.length,
|
||||
primaryKeys,
|
||||
elapsed: elapsed(),
|
||||
});
|
||||
queryStore.setTableMeta(tabId, {
|
||||
schema: tableSchema,
|
||||
tableName: node.label,
|
||||
columns,
|
||||
primaryKeys,
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn("[DBX][openData:get-columns:error]", { traceId, elapsed: elapsed(), error });
|
||||
}
|
||||
|
||||
const includeRowId = usesSyntheticRowIdKey(effectiveDbType, primaryKeys);
|
||||
const fallbackOrderColumns = effectiveDbType === "sqlserver" && !primaryKeys.length ? columns.slice(0, 1).map((column) => column.name) : undefined;
|
||||
const sql = await buildTableSelectSql({
|
||||
databaseType: effectiveDbType,
|
||||
schema: tableSchema,
|
||||
tableName: node.label,
|
||||
columns: [],
|
||||
primaryKeys: [],
|
||||
columns: columns.map((column) => column.name),
|
||||
primaryKeys,
|
||||
fallbackOrderColumns,
|
||||
limit,
|
||||
includeRowId: false,
|
||||
includeRowId,
|
||||
});
|
||||
console.info("[DBX][openData:sql-built]", {
|
||||
traceId,
|
||||
primaryKeys: [],
|
||||
includeRowId: false,
|
||||
primaryKeys,
|
||||
includeRowId,
|
||||
sql,
|
||||
elapsed: elapsed(),
|
||||
});
|
||||
queryStore.updateSql(tabId, sql);
|
||||
|
||||
const loadTableMeta = async () => {
|
||||
try {
|
||||
console.info("[DBX][openData:get-columns:start]", {
|
||||
traceId,
|
||||
database: node.database,
|
||||
schema: querySchema,
|
||||
table: node.label,
|
||||
elapsed: elapsed(),
|
||||
});
|
||||
const columns = await api.getColumns(node.connectionId, node.database, querySchema, node.label);
|
||||
console.info("[DBX][openData:get-columns:done]", {
|
||||
traceId,
|
||||
columnCount: columns.length,
|
||||
primaryKeys: columns.filter((column) => column.is_primary_key).map((column) => column.name),
|
||||
elapsed: elapsed(),
|
||||
});
|
||||
const pks = editablePrimaryKeys(effectiveDbType, columns);
|
||||
queryStore.setTableMeta(tabId, {
|
||||
schema: tableSchema,
|
||||
tableName: node.label,
|
||||
columns,
|
||||
primaryKeys: pks,
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn("[DBX][openData:get-columns:error]", { traceId, elapsed: elapsed(), error });
|
||||
}
|
||||
};
|
||||
|
||||
console.info("[DBX][openData:execute:start]", { traceId, tabId, elapsed: elapsed() });
|
||||
await queryStore.executeTabSql(tabId, sql);
|
||||
console.info("[DBX][openData:execute:done]", { traceId, tabId, elapsed: elapsed() });
|
||||
void loadTableMeta();
|
||||
} catch (e: any) {
|
||||
console.error("[DBX][openData:error]", { traceId, elapsed: elapsed(), error: e });
|
||||
queryStore.setErrorResult(tabId, e);
|
||||
@@ -2358,6 +2360,11 @@ function newConnectionInGroup() {
|
||||
connectionStore.startCreatingConnectionInGroup(props.node.id);
|
||||
}
|
||||
|
||||
function newSubgroup() {
|
||||
const groupId = connectionStore.createConnectionGroup(t("connectionGroup.newGroupDefault"), props.node.id);
|
||||
connectionStore.selectedTreeNodeId = groupId;
|
||||
}
|
||||
|
||||
function confirmDeleteGroup() {
|
||||
connectionStore.deleteConnectionGroup(props.node.id);
|
||||
showDeleteGroupConfirm.value = false;
|
||||
@@ -2393,12 +2400,18 @@ const availableGroups = computed(() => connectionStore.sidebarLayout.groups);
|
||||
|
||||
const currentGroupId = computed(() => {
|
||||
if (props.node.type !== "connection" || !props.node.connectionId) return null;
|
||||
for (const entry of connectionStore.sidebarLayout.order) {
|
||||
if (entry.type === "group" && entry.connectionIds.includes(props.node.connectionId)) {
|
||||
return entry.id;
|
||||
const find = (entries: typeof connectionStore.sidebarLayout.order): string | null => {
|
||||
for (const entry of entries) {
|
||||
if (entry.type !== "group") continue;
|
||||
if ((entry.children ?? entry.connectionIds?.map((id) => ({ type: "connection" as const, id })) ?? []).some((child) => child.type === "connection" && child.id === props.node.connectionId)) {
|
||||
return entry.id;
|
||||
}
|
||||
const found = find(entry.children ?? []);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return null;
|
||||
};
|
||||
return find(connectionStore.sidebarLayout.order);
|
||||
});
|
||||
|
||||
// --- Drag and Drop ---
|
||||
@@ -2697,7 +2710,10 @@ function treeItemMenuItems(): ContextMenuItem[] {
|
||||
|
||||
// 3. Connection Group
|
||||
if (node.type === "connection-group") {
|
||||
items.push({ label: t("contextMenu.copyName"), action: copyName, icon: Copy, shortcut: shortcutCopyName.value });
|
||||
items.push({ label: "", separator: true });
|
||||
items.push({ label: t("toolbar.newConnection"), action: newConnectionInGroup, icon: Plus });
|
||||
items.push({ label: t("connectionGroup.newGroup"), action: newSubgroup, icon: FolderPlus });
|
||||
items.push({ label: "", separator: true });
|
||||
items.push({
|
||||
label: t("connectionGroup.renameGroup"),
|
||||
@@ -2718,6 +2734,8 @@ function treeItemMenuItems(): ContextMenuItem[] {
|
||||
|
||||
// 4. Database / Schema
|
||||
if (node.type === "database" || node.type === "schema") {
|
||||
items.push({ label: t("contextMenu.copyName"), action: copyName, icon: Copy, shortcut: shortcutCopyName.value });
|
||||
items.push({ label: "", separator: true });
|
||||
if (canOpenObjectBrowser.value) {
|
||||
items.push({ label: t("contextMenu.openObjectBrowser"), action: openObjectBrowser, icon: TableProperties });
|
||||
}
|
||||
|
||||
@@ -101,10 +101,16 @@ function toggleDatabase(database: string) {
|
||||
selectedNames.value = next;
|
||||
}
|
||||
|
||||
const isSearching = computed(() => searchText.value.trim().length > 0);
|
||||
|
||||
function selectAll() {
|
||||
selectedNames.value = new Set(listedDatabaseNames.value);
|
||||
}
|
||||
|
||||
function selectFiltered() {
|
||||
selectedNames.value = new Set(filteredDatabaseNames.value);
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
selectedNames.value = new Set();
|
||||
}
|
||||
@@ -142,6 +148,9 @@ async function saveSelection() {
|
||||
<button class="hover:text-foreground disabled:opacity-50" :disabled="isLoading" @click="selectAll">
|
||||
{{ t("visibleDatabases.selectAll") }}
|
||||
</button>
|
||||
<button v-if="isSearching" class="hover:text-foreground disabled:opacity-50" :disabled="isLoading" @click="selectFiltered">
|
||||
{{ t("visibleDatabases.selectFiltered") }}
|
||||
</button>
|
||||
<button class="hover:text-foreground disabled:opacity-50" :disabled="isLoading" @click="clearSelection">
|
||||
{{ t("visibleDatabases.clear") }}
|
||||
</button>
|
||||
|
||||
@@ -25,7 +25,7 @@ import { type EditableStructureColumn, type EditableStructureIndex } from "@/lib
|
||||
import { getTableMetadataCapabilities } from "@/lib/tableMetadataCapabilities";
|
||||
import { getTableStructureCapabilities } from "@/lib/tableStructureCapabilities";
|
||||
import { connectionObjectTreeQuerySchema, effectiveDatabaseTypeForConnection } from "@/lib/jdbcDialect";
|
||||
import { buildStructureTargetLabel, combineDataTypeForDatabase, createColumnDrafts, createIndexDrafts, getDataTypeOptions, getDefaultLengthForType, splitDataType, toColumnNames } from "@/lib/tableStructureEditorState";
|
||||
import { buildStructureTargetLabel, combineDataTypeForDatabase, createColumnDrafts, createIndexDrafts, generateIndexName, generateUniqueIndexName, getDataTypeOptions, getDefaultLengthForType, splitDataType, toColumnNames } from "@/lib/tableStructureEditorState";
|
||||
import type { ForeignKeyInfo, TriggerInfo } from "@/types/database";
|
||||
import * as api from "@/lib/api";
|
||||
|
||||
@@ -482,6 +482,7 @@ function addIndex() {
|
||||
id: `new:${uuid()}`,
|
||||
name: "",
|
||||
columns: [],
|
||||
nameEdited: false,
|
||||
isUnique: false,
|
||||
isPrimary: false,
|
||||
filter: "",
|
||||
@@ -500,6 +501,32 @@ function addIndex() {
|
||||
});
|
||||
}
|
||||
|
||||
function structureIndexTableName(): string {
|
||||
return (isCreateMode.value ? newTableName.value : props.tableName).trim();
|
||||
}
|
||||
|
||||
function existingIndexNamesForDraft(index: EditableStructureIndex): string[] {
|
||||
return indexes.value.filter((item) => item.id !== index.id && !item.markedForDrop).map((item) => item.name);
|
||||
}
|
||||
|
||||
function generatedIndexNameForDraft(index: EditableStructureIndex, columnsForName = index.columns): string {
|
||||
return generateUniqueIndexName(structureIndexTableName(), columnsForName, existingIndexNamesForDraft(index));
|
||||
}
|
||||
|
||||
function refreshAutoIndexName(index: EditableStructureIndex, previousColumns = index.columns) {
|
||||
if (index.original || index.nameEdited) return;
|
||||
const previousName = generateIndexName(structureIndexTableName(), previousColumns);
|
||||
const previousUniqueName = generateUniqueIndexName(structureIndexTableName(), previousColumns, existingIndexNamesForDraft(index));
|
||||
const currentName = index.name.trim();
|
||||
if (currentName && currentName !== previousName && currentName !== previousUniqueName) return;
|
||||
index.name = generatedIndexNameForDraft(index);
|
||||
}
|
||||
|
||||
function onIndexNameInput(index: EditableStructureIndex, value: string | number) {
|
||||
index.name = String(value ?? "");
|
||||
index.nameEdited = true;
|
||||
}
|
||||
|
||||
const availableColumnNames = computed(() =>
|
||||
columns.value
|
||||
.filter((c) => !c.markedForDrop)
|
||||
@@ -515,9 +542,11 @@ const filteredColumnNames = computed(() => {
|
||||
});
|
||||
|
||||
function toggleIndexColumn(index: EditableStructureIndex, col: string) {
|
||||
const previousColumns = [...index.columns];
|
||||
const i = index.columns.indexOf(col);
|
||||
if (i >= 0) index.columns.splice(i, 1);
|
||||
else index.columns.push(col);
|
||||
refreshAutoIndexName(index, previousColumns);
|
||||
}
|
||||
|
||||
function toggleIncludedColumn(index: EditableStructureIndex, col: string) {
|
||||
@@ -699,6 +728,12 @@ watch(
|
||||
{ deep: true, immediate: true },
|
||||
);
|
||||
|
||||
watch([() => props.tableName, newTableName], () => {
|
||||
for (const index of indexes.value) {
|
||||
refreshAutoIndexName(index);
|
||||
}
|
||||
});
|
||||
|
||||
watch(refreshVersion, (version, previous) => {
|
||||
if (version === previous || !version || isCreateMode.value) return;
|
||||
void loadStructure(true);
|
||||
@@ -1019,7 +1054,7 @@ watch(activeTab, (tab) => {
|
||||
<tbody>
|
||||
<tr v-for="index in indexes" :key="index.id" :class="index.markedForDrop ? 'bg-destructive/5 opacity-60' : ''" :data-new-index-row="!index.original ? 'true' : undefined">
|
||||
<td :class="structureCellClass">
|
||||
<Input v-model="index.name" :class="structureControlClass" :disabled="!canEditIndexDraft(index)" data-index-name-input />
|
||||
<Input :model-value="index.name" :class="structureControlClass" :disabled="!canEditIndexDraft(index)" data-index-name-input @update:model-value="(value: string | number) => onIndexNameInput(index, value)" />
|
||||
</td>
|
||||
<td :class="[structureCellClass, 'overflow-hidden']">
|
||||
<DropdownMenu v-if="canEditIndexDraft(index)">
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { Copy, TriangleAlert } from "@lucide/vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { copyToClipboard } from "@/lib/clipboard";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
|
||||
const { t } = useI18n();
|
||||
const { toast } = useToast();
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
message: string;
|
||||
variant?: "banner" | "centered";
|
||||
title?: string;
|
||||
}>(),
|
||||
{
|
||||
variant: "banner",
|
||||
},
|
||||
);
|
||||
|
||||
const displayTitle = computed(() => props.title ?? t("grid.queryError"));
|
||||
|
||||
async function copy() {
|
||||
try {
|
||||
await copyToClipboard(props.message);
|
||||
toast(t("grid.copied"));
|
||||
} catch (e: any) {
|
||||
toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- banner: 紧凑内联横幅 -->
|
||||
<div v-if="variant === 'banner'" class="flex items-center gap-2 px-3 py-1.5 border-t bg-destructive/10 text-destructive text-xs shrink-0">
|
||||
<span class="flex-1 min-w-0 break-all">{{ message }}</span>
|
||||
<Button variant="ghost" size="icon-sm" class="h-5 w-5 shrink-0 text-destructive/70 hover:text-destructive" :aria-label="t('grid.copy')" @click.stop="copy">
|
||||
<Copy class="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- centered: 居中占满 -->
|
||||
<div v-else class="flex-1 flex flex-col items-center justify-center gap-2 px-6 text-center text-destructive">
|
||||
<TriangleAlert class="h-8 w-8 text-destructive/50" aria-hidden="true" />
|
||||
<div class="space-y-1 select-text" @mousedown.stop @click.stop>
|
||||
<div class="text-sm font-medium">{{ displayTitle }}</div>
|
||||
<div class="text-xs max-w-lg break-all cursor-text text-destructive/80 select-text">{{ message }}</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-center gap-2">
|
||||
<Button variant="outline" size="sm" class="h-7 gap-1.5 px-2 text-xs" @click.stop="copy">
|
||||
<Copy class="h-3.5 w-3.5" />
|
||||
{{ t("grid.copy") }}
|
||||
</Button>
|
||||
<slot name="actions" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -30,6 +30,11 @@ type GridScrollerRef =
|
||||
scrollToPosition?: (position: number) => void;
|
||||
};
|
||||
|
||||
export interface CustomSaveHandler {
|
||||
save: (changes: { dirtyRows: Map<number, Map<number, CellValue>>; newRows: CellValue[][]; deletedRows: Set<number>; columns: string[]; rows: CellValue[][] }) => Promise<void>;
|
||||
preview?: (changes: { dirtyRows: Map<number, Map<number, CellValue>>; newRows: CellValue[][]; deletedRows: Set<number>; columns: string[]; rows: CellValue[][] }) => Promise<string[]>;
|
||||
}
|
||||
|
||||
export interface UseDataGridEditorOptions {
|
||||
result: ComputedRef<{ columns: string[]; rows: CellValue[][] }>;
|
||||
editable: ComputedRef<boolean | undefined>;
|
||||
@@ -48,7 +53,7 @@ export interface UseDataGridEditorOptions {
|
||||
sourceColumns?: ComputedRef<Array<string | undefined> | undefined>;
|
||||
canEditExistingRows?: ComputedRef<boolean>;
|
||||
onExecuteSql: ComputedRef<((sql: string) => Promise<void>) | undefined>;
|
||||
customSave?: ComputedRef<((changes: { dirtyRows: Map<number, Map<number, CellValue>>; newRows: CellValue[][]; deletedRows: Set<number>; columns: string[]; rows: CellValue[][] }) => Promise<void>) | undefined>;
|
||||
customSaveHandler?: ComputedRef<CustomSaveHandler | undefined>;
|
||||
sql: ComputedRef<string | undefined>;
|
||||
searchText: Ref<string>;
|
||||
whereFilterInput: Ref<string>;
|
||||
@@ -119,7 +124,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
sourceColumns = computed(() => undefined),
|
||||
canEditExistingRows = computed(() => true),
|
||||
onExecuteSql,
|
||||
customSave,
|
||||
customSaveHandler,
|
||||
sql,
|
||||
searchText,
|
||||
orderByInput,
|
||||
@@ -174,7 +179,8 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
const isSaving = ref(false);
|
||||
const saveError = ref("");
|
||||
|
||||
const useTransaction = computed(() => editable.value && supportsDataGridTransaction(databaseType.value) && (!!customSave?.value || (!!connectionId.value && !!database.value && !!tableMeta.value)));
|
||||
const hasBackendSaveTarget = computed(() => !!connectionId.value && !!tableMeta.value);
|
||||
const useTransaction = computed(() => editable.value && supportsDataGridTransaction(databaseType.value) && (!!customSaveHandler?.value || hasBackendSaveTarget.value));
|
||||
|
||||
if (hasPendingChanges.value && useTransaction.value) {
|
||||
transactionActive.value = true;
|
||||
@@ -218,6 +224,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
|
||||
// --- Scroll helpers ---
|
||||
let isCancelling = false;
|
||||
let isCommitting = false;
|
||||
let cancelScrollRestoreFrame = 0;
|
||||
let resetScrollFrame = 0;
|
||||
let resetScrollAfterResult = false;
|
||||
@@ -391,12 +398,14 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
}
|
||||
|
||||
function commitEdit() {
|
||||
if (isCancelling) return;
|
||||
if (isCancelling || isCommitting) return;
|
||||
if (!editingCell.value) return;
|
||||
isCommitting = true;
|
||||
const { rowId, col } = editingCell.value;
|
||||
const item = getRowItem(rowId);
|
||||
if (!item || item.isDeleted) {
|
||||
editingCell.value = null;
|
||||
isCommitting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -407,15 +416,18 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
newRows.value[item.newIndex][col] = newVal;
|
||||
}
|
||||
editingCell.value = null;
|
||||
isCommitting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (item.sourceIndex === undefined) {
|
||||
editingCell.value = null;
|
||||
isCommitting = false;
|
||||
return;
|
||||
}
|
||||
if (!canEditExistingRows.value) {
|
||||
editingCell.value = null;
|
||||
isCommitting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -434,6 +446,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
}
|
||||
dirtyRows.value = new Map(dirtyRows.value);
|
||||
editingCell.value = null;
|
||||
isCommitting = false;
|
||||
}
|
||||
|
||||
function commitEditFromBlur() {
|
||||
@@ -643,7 +656,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
}
|
||||
|
||||
async function recordDataGridHistory(statements: string[], rollbackStatements: string[], elapsed: number, historyResult?: { affected_rows?: number; success?: boolean; error?: string }) {
|
||||
if (!connectionId.value || !database.value || !tableMeta.value) return;
|
||||
if (!connectionId.value || !tableMeta.value) return;
|
||||
const connName = connectionStore.getConfig(connectionId.value)?.name || "";
|
||||
const success = historyResult?.success ?? true;
|
||||
const details = {
|
||||
@@ -659,7 +672,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
await historyStore.add({
|
||||
connection_id: connectionId.value,
|
||||
connection_name: connName,
|
||||
database: database.value,
|
||||
database: database.value ?? "",
|
||||
sql: statements.join("\n"),
|
||||
execution_time_ms: elapsed,
|
||||
success,
|
||||
@@ -695,9 +708,9 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
isSaving.value = true;
|
||||
const shouldReloadAfterSave = newRows.value.length > 0 || deletedRows.value.size > 0;
|
||||
|
||||
if (customSave?.value) {
|
||||
if (customSaveHandler?.value) {
|
||||
try {
|
||||
await customSave.value({
|
||||
await customSaveHandler.value.save({
|
||||
dirtyRows: dirtyRows.value,
|
||||
newRows: newRows.value,
|
||||
deletedRows: deletedRows.value,
|
||||
@@ -752,17 +765,17 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
rollbackStatements: rollbackStmts,
|
||||
});
|
||||
|
||||
if (useTransaction.value && connectionId.value && database.value) {
|
||||
if (useTransaction.value && hasBackendSaveTarget.value) {
|
||||
try {
|
||||
apiResult = await api.executeInTransaction(connectionId.value, database.value, stmts, preparedSave?.executionSchema);
|
||||
apiResult = await api.executeInTransaction(connectionId.value!, database.value ?? "", stmts, preparedSave?.executionSchema);
|
||||
} catch (e: any) {
|
||||
saveError.value = await recordFailedDataGridHistory(stmts, rollbackStmts, start, e);
|
||||
isSaving.value = false;
|
||||
return;
|
||||
}
|
||||
} else if (connectionId.value && database.value) {
|
||||
} else if (hasBackendSaveTarget.value) {
|
||||
try {
|
||||
apiResult = await api.executeBatch(connectionId.value, database.value, stmts);
|
||||
apiResult = await api.executeBatch(connectionId.value!, database.value ?? "", stmts, preparedSave?.executionSchema);
|
||||
} catch (e: any) {
|
||||
saveError.value = await recordFailedDataGridHistory(stmts, rollbackStmts, start, e);
|
||||
isSaving.value = false;
|
||||
@@ -896,8 +909,9 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
isPreviewLoading.value = true;
|
||||
previewStatements.value = [];
|
||||
try {
|
||||
if (customSave?.value) {
|
||||
// customSave doesn't expose SQL — return empty
|
||||
if (customSaveHandler?.value) {
|
||||
const preview = customSaveHandler.value.preview;
|
||||
if (preview) return await preview({ dirtyRows: dirtyRows.value, newRows: newRows.value, deletedRows: deletedRows.value, columns: result.value.columns, rows: result.value.rows });
|
||||
return [];
|
||||
}
|
||||
const stmtOptions = saveStatementOptions();
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useSettingsStore } from "@/stores/settingsStore";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
import { classifySqlActivityKind } from "@/lib/historyActivityKind";
|
||||
import { sqlMetadataRefreshTarget } from "@/lib/sqlMetadataRefresh";
|
||||
import { classifyRedisCommandSafety, firstRedisCommandToken } from "@/lib/redisCommandSafety";
|
||||
import type { ConnectionConfig, QueryTab } from "@/types/database";
|
||||
|
||||
const DANGER_RE = /^\s*(DROP|DELETE|TRUNCATE|ALTER|UPDATE|MERGE|REPLACE)\b/i;
|
||||
@@ -32,7 +33,14 @@ function primarySqlOperation(sql: string): string {
|
||||
return statement?.match(/^([a-z]+)/i)?.[1]?.toUpperCase() || "SQL";
|
||||
}
|
||||
|
||||
export function useSqlExecution(deps: { activeTab: ComputedRef<QueryTab | undefined>; activeConnection: ComputedRef<ConnectionConfig | undefined>; executableSql: ComputedRef<string>; resolveExecutableSql?: () => Promise<string>; activeOutputView: Ref<"result" | "summary" | "explain" | "chart"> }) {
|
||||
export function useSqlExecution(deps: {
|
||||
activeTab: ComputedRef<QueryTab | undefined>;
|
||||
activeConnection: ComputedRef<ConnectionConfig | undefined>;
|
||||
executableSql: ComputedRef<string>;
|
||||
resolveExecutableSql?: () => Promise<string>;
|
||||
activeOutputView: Ref<"result" | "summary" | "explain" | "chart">;
|
||||
blockDangerousRedisCommands?: Ref<boolean>;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const queryStore = useQueryStore();
|
||||
const historyStore = useHistoryStore();
|
||||
@@ -54,6 +62,14 @@ export function useSqlExecution(deps: { activeTab: ComputedRef<QueryTab | undefi
|
||||
const tab = deps.activeTab.value;
|
||||
const sql = sqlOverride ?? (await resolvedExecutableSql());
|
||||
if (!tab || !sql.trim()) return;
|
||||
// Redis: block dangerous commands when toggle is on
|
||||
if (deps.activeConnection.value?.db_type === "redis" && deps.blockDangerousRedisCommands?.value !== false) {
|
||||
const safety = classifyRedisCommandSafety(sql);
|
||||
if (safety === "blocked") {
|
||||
toast(t("redis.blockedCommand", { command: firstRedisCommandToken(sql) }), 5000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (isDangerousSql(sql) && settingsStore.editorSettings.confirmDangerousSqlExecution) {
|
||||
dangerSql.value = sql;
|
||||
pendingDangerSql.value = sql;
|
||||
@@ -71,7 +87,8 @@ export function useSqlExecution(deps: { activeTab: ComputedRef<QueryTab | undefi
|
||||
deps.activeOutputView.value = "result";
|
||||
const connName = connectionStore.getConfig(tab.connectionId)?.name || "";
|
||||
const start = Date.now();
|
||||
await queryStore.executeCurrentSql(sql);
|
||||
const isRedis = deps.activeConnection.value?.db_type === "redis";
|
||||
await queryStore.executeCurrentSql(sql, isRedis ? { skipRedisSafetyCheck: deps.blockDangerousRedisCommands?.value === false } : undefined);
|
||||
if (tab.result && !tab.result.columns.length && !tab.results?.some((result) => result.columns.length > 0)) {
|
||||
deps.activeOutputView.value = "summary";
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
sqlSaveFailed: "Failed to save file: {message}",
|
||||
driverManager: "Driver Manager",
|
||||
updatableDriverCount: "Updatable driver count",
|
||||
blockDangerousRedisCommands: "Block dangerous commands",
|
||||
},
|
||||
updates: {
|
||||
title: "Updates",
|
||||
@@ -317,6 +318,8 @@
|
||||
jdbcDriverClassPlaceholder: "Most drivers auto-register; use com.vendor.jdbc.Driver if needed",
|
||||
jdbcDriverPaths: "Driver JARs",
|
||||
jdbcDriverSelectPlaceholder: "Choose imported driver",
|
||||
jdbcManualClasspath: "Manual classpath",
|
||||
jdbcManualClasspathCount: "{count} paths",
|
||||
jdbcDriverPathsPlaceholder: "/path/to/driver.jar\n/path/to/another-driver.jar",
|
||||
jdbcDriverBrowse: "Choose JDBC driver JAR",
|
||||
jdbcDocs: "View JDBC docs",
|
||||
@@ -344,6 +347,9 @@
|
||||
showResultsPane: "Show results",
|
||||
hideResultsPane: "Hide results",
|
||||
noDatabase: "No database selected",
|
||||
unsavedChangesTitle: "Unsaved changes",
|
||||
unsavedChangesMessage: "This tab has unsaved changes that will be lost if closed. Save before closing?",
|
||||
discardChanges: "Discard",
|
||||
selectConnection: "Select connection",
|
||||
searchConnection: "Search connections...",
|
||||
selectDatabase: "Select database",
|
||||
@@ -1158,6 +1164,7 @@
|
||||
searchPlaceholder: "Search databases...",
|
||||
selectedCount: "{selected}/{total} selected",
|
||||
selectAll: "Select all",
|
||||
selectFiltered: "Select search results",
|
||||
clear: "Clear",
|
||||
showAll: "Show all",
|
||||
showSystemDatabases: "Show system databases",
|
||||
@@ -1468,6 +1475,7 @@
|
||||
jsonFormatError: "Invalid JSON format",
|
||||
clearHistory: "Clear command history",
|
||||
historyCleared: "Redis command history cleared",
|
||||
blockedCommand: "Command {command} is blocked for safety. Disable the shield icon in the toolbar to allow.",
|
||||
},
|
||||
mongo: {
|
||||
documents: "{count} documents",
|
||||
@@ -2079,6 +2087,8 @@
|
||||
progressJreExtract: "Extracting JRE...",
|
||||
progressDownloadJre: "Downloading JRE",
|
||||
progressDownloadDriver: "Downloading driver",
|
||||
progressDownloadJdbcPlugin: "Downloading JDBC plugin",
|
||||
progressJdbcPluginExtract: "Installing JDBC plugin...",
|
||||
usageTitle: "Storage usage",
|
||||
usageTotal: "Total {size}",
|
||||
usageTotalLabel: "Total",
|
||||
@@ -2091,6 +2101,11 @@
|
||||
offlineDownloadLink: "Offline driver downloads",
|
||||
searchDrivers: "Search driver name, type, version...",
|
||||
searchJdbcDrivers: "Search JDBC driver name or path...",
|
||||
jdbcMavenCoordinatePlaceholder: "Maven coordinate, e.g. org.postgresql:postgresql:42.7.7",
|
||||
jdbcMavenInstall: "Install from Maven",
|
||||
jdbcMavenInstallSuccess: "JDBC Maven driver installed",
|
||||
jdbcSourceMaven: "Maven",
|
||||
jdbcSourceManual: "Manual",
|
||||
noMatchingDrivers: "No matching drivers.",
|
||||
javaRuntimeSaved: "Java runtime settings saved",
|
||||
javaRuntimeSaveFailed: "Failed to save Java runtime settings: {error}",
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
sqlSaveFailed: "Error al guardar el archivo: {message}",
|
||||
driverManager: "Administrador de drivers",
|
||||
updatableDriverCount: "Cantidad de drivers actualizables",
|
||||
blockDangerousRedisCommands: "Bloquear comandos peligrosos",
|
||||
},
|
||||
updates: {
|
||||
title: "Actualizaciones",
|
||||
@@ -1249,6 +1250,7 @@
|
||||
wordWrap: "Ajuste de línea",
|
||||
clearHistory: "Borrar historial de comandos",
|
||||
historyCleared: "Historial de comandos Redis borrado",
|
||||
blockedCommand: "El comando {command} está bloqueado por seguridad. Desactiva el icono de escudo en la barra de herramientas para permitirlo.",
|
||||
},
|
||||
mongo: {
|
||||
documents: "{count} documentos",
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
sqlSaveFailed: "Impossibile salvare il file: {message}",
|
||||
driverManager: "Gestione Driver",
|
||||
updatableDriverCount: "Driver aggiornabili",
|
||||
blockDangerousRedisCommands: "Blocca comandi pericolosi",
|
||||
},
|
||||
updates: {
|
||||
title: "Aggiornamenti",
|
||||
@@ -1361,6 +1362,7 @@
|
||||
wordWrap: "A capo automatico",
|
||||
clearHistory: "Cancella cronologia comandi",
|
||||
historyCleared: "Cronologia comandi Redis cancellata",
|
||||
blockedCommand: "Il comando {command} è bloccato per sicurezza. Disattiva l'icona scudo nella barra degli strumenti per consentirlo.",
|
||||
},
|
||||
mongo: {
|
||||
documents: "{count} documenti",
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
sqlSaveFailed: "Falha ao salvar o arquivo: {message}",
|
||||
driverManager: "Gerenciador de Drivers",
|
||||
updatableDriverCount: "Quantidade de drivers atualizáveis",
|
||||
blockDangerousRedisCommands: "Bloquear comandos perigosos",
|
||||
},
|
||||
updates: {
|
||||
title: "Atualizações",
|
||||
@@ -1361,6 +1362,7 @@
|
||||
wordWrap: "Quebra de linha",
|
||||
clearHistory: "Limpar histórico de comandos",
|
||||
historyCleared: "Histórico de comandos Redis limpo",
|
||||
blockedCommand: "O comando {command} está bloqueado por segurança. Desative o ícone de escudo na barra de ferramentas para permiti-lo.",
|
||||
},
|
||||
mongo: {
|
||||
documents: "{count} documentos",
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
sqlSaveFailed: "保存文件失败:{message}",
|
||||
driverManager: "驱动管理",
|
||||
updatableDriverCount: "可更新驱动数量",
|
||||
blockDangerousRedisCommands: "拦截危险命令",
|
||||
},
|
||||
updates: {
|
||||
title: "更新",
|
||||
@@ -318,6 +319,8 @@
|
||||
jdbcDriverClassPlaceholder: "多数驱动可自动识别;需要时填写 com.vendor.jdbc.Driver",
|
||||
jdbcDriverPaths: "驱动 JAR",
|
||||
jdbcDriverSelectPlaceholder: "选择已导入驱动",
|
||||
jdbcManualClasspath: "手动 classpath",
|
||||
jdbcManualClasspathCount: "{count} 个路径",
|
||||
jdbcDriverPathsPlaceholder: "/path/to/driver.jar\n/path/to/another-driver.jar",
|
||||
jdbcDriverBrowse: "选择 JDBC 驱动 JAR",
|
||||
jdbcDocs: "查看 JDBC 文档",
|
||||
@@ -345,6 +348,9 @@
|
||||
showResultsPane: "显示结果",
|
||||
hideResultsPane: "收起结果",
|
||||
noDatabase: "未选择数据库",
|
||||
unsavedChangesTitle: "未保存的更改",
|
||||
unsavedChangesMessage: "此标签页有未保存的更改,关闭后将丢失。是否保存后再关闭?",
|
||||
discardChanges: "不保存",
|
||||
selectConnection: "选择连接",
|
||||
searchConnection: "搜索连接...",
|
||||
selectDatabase: "选择数据库",
|
||||
@@ -1157,6 +1163,7 @@
|
||||
searchPlaceholder: "搜索数据库...",
|
||||
selectedCount: "已选择 {selected}/{total}",
|
||||
selectAll: "全选",
|
||||
selectFiltered: "选中搜索结果",
|
||||
clear: "清空",
|
||||
showAll: "显示全部",
|
||||
showSystemDatabases: "显示系统库",
|
||||
@@ -1467,6 +1474,7 @@
|
||||
jsonFormatError: "JSON 格式不合法",
|
||||
clearHistory: "清除命令历史",
|
||||
historyCleared: "Redis 命令历史已清除",
|
||||
blockedCommand: "命令 {command} 因安全原因已被拦截。点击工具栏盾牌图标可关闭拦截。",
|
||||
},
|
||||
mongo: {
|
||||
documents: "{count} 个文档",
|
||||
@@ -2078,6 +2086,8 @@
|
||||
progressJreExtract: "解压 JRE...",
|
||||
progressDownloadJre: "下载 JRE",
|
||||
progressDownloadDriver: "下载驱动",
|
||||
progressDownloadJdbcPlugin: "下载 JDBC 插件",
|
||||
progressJdbcPluginExtract: "安装 JDBC 插件...",
|
||||
usageTitle: "空间占用明细",
|
||||
usageTotal: "总计 {size}",
|
||||
usageTotalLabel: "总计",
|
||||
@@ -2090,6 +2100,11 @@
|
||||
offlineDownloadLink: "离线驱动下载",
|
||||
searchDrivers: "搜索驱动名称、类型、版本...",
|
||||
searchJdbcDrivers: "搜索 JDBC 驱动名称或路径...",
|
||||
jdbcMavenCoordinatePlaceholder: "Maven 坐标,例如 org.postgresql:postgresql:42.7.7",
|
||||
jdbcMavenInstall: "从 Maven 安装",
|
||||
jdbcMavenInstallSuccess: "JDBC Maven 驱动已安装",
|
||||
jdbcSourceMaven: "Maven",
|
||||
jdbcSourceManual: "手动",
|
||||
noMatchingDrivers: "没有匹配的驱动。",
|
||||
javaRuntimeSaved: "Java 运行时设置已保存",
|
||||
javaRuntimeSaveFailed: "Java 运行时设置失败: {error}",
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
sqlSaveFailed: "儲存檔案失敗:{message}",
|
||||
driverManager: "驅動程式管理器",
|
||||
updatableDriverCount: "可更新驅動程式數量",
|
||||
blockDangerousRedisCommands: "攔截危險命令",
|
||||
},
|
||||
updates: {
|
||||
title: "更新",
|
||||
@@ -1338,6 +1339,7 @@
|
||||
wordWrap: "自動換行",
|
||||
clearHistory: "清除命令歷史",
|
||||
historyCleared: "Redis 命令歷史已清除",
|
||||
blockedCommand: "命令 {command} 因安全原因已被攔截。點擊工具列盾牌圖示可關閉攔截。",
|
||||
},
|
||||
mongo: {
|
||||
documents: "{count} 個文件",
|
||||
|
||||
@@ -62,8 +62,11 @@ export const readKeychainPasswords = forward("readKeychainPasswords");
|
||||
export const decryptConfig = forward("decryptConfig");
|
||||
export const listPlugins = forward("listPlugins");
|
||||
export const listJdbcDrivers = forward("listJdbcDrivers");
|
||||
export const listJdbcMavenBundles = forward("listJdbcMavenBundles");
|
||||
export const importJdbcDrivers = forward("importJdbcDrivers");
|
||||
export const installJdbcDriverFromMaven = forward("installJdbcDriverFromMaven");
|
||||
export const deleteJdbcDriver = forward("deleteJdbcDriver");
|
||||
export const deleteJdbcMavenBundle = forward("deleteJdbcMavenBundle");
|
||||
export const jdbcPluginStatus = forward("jdbcPluginStatus");
|
||||
export const installJdbcPlugin = forward("installJdbcPlugin");
|
||||
export const installJdbcPluginLocal = forward("installJdbcPluginLocal");
|
||||
@@ -258,6 +261,7 @@ export const etcdDelete = forward("etcdDelete");
|
||||
// MongoDB
|
||||
export const mongoListDatabases = forward("mongoListDatabases");
|
||||
export const mongoListCollections = forward("mongoListCollections");
|
||||
export const documentFindDocuments = forward("documentFindDocuments");
|
||||
export const mongoFindDocuments = forward("mongoFindDocuments");
|
||||
export const mongoAggregateDocuments = forward("mongoAggregateDocuments");
|
||||
export const mongoInsertDocument = forward("mongoInsertDocument");
|
||||
|
||||
@@ -395,7 +395,7 @@ export function drawCanvasDataGrid(options: DrawCanvasDataGridOptions) {
|
||||
const selectedLeftX = clippedX + 0.5;
|
||||
const selectedRightX = clippedX + cellPaintWidth - 1.5;
|
||||
const selectedTopY = Math.max(y + 0.5, 1);
|
||||
const drawSelectedLeftBorder = selectedLeftX > rowNumberWidth + 0.5;
|
||||
const drawSelectedLeftBorder = selectedLeftX >= rowNumberWidth + 0.5;
|
||||
ctx.strokeStyle = theme.cellSelectedBorder;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(selectedLeftX, selectedTopY);
|
||||
|
||||
@@ -2,14 +2,51 @@ import type { ConnectionConfig } from "@/types/database";
|
||||
|
||||
export const CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS = 2_000;
|
||||
export const MONGO_LEGACY_FALLBACK_TIMEOUT_BUFFER_MS = 30_000;
|
||||
export const AGENT_DRIVER_MIN_CONNECT_TIMEOUT_SECS = 15;
|
||||
const DEFAULT_CONNECT_TIMEOUT_SECS = 5;
|
||||
|
||||
const AGENT_DRIVER_TYPES = new Set<DatabaseType>([
|
||||
"dameng",
|
||||
"kingbase",
|
||||
"highgo",
|
||||
"vastbase",
|
||||
"goldendb",
|
||||
"yashandb",
|
||||
"databricks",
|
||||
"saphana",
|
||||
"teradata",
|
||||
"vertica",
|
||||
"firebird",
|
||||
"exasol",
|
||||
"oceanbase-oracle",
|
||||
"gbase",
|
||||
"access",
|
||||
"oracle",
|
||||
"h2",
|
||||
"snowflake",
|
||||
"trino",
|
||||
"hive",
|
||||
"db2",
|
||||
"informix",
|
||||
"neo4j",
|
||||
"cassandra",
|
||||
"bigquery",
|
||||
"kylin",
|
||||
"sundb",
|
||||
"tdengine",
|
||||
"xugu",
|
||||
"iotdb",
|
||||
"etcd",
|
||||
"iris",
|
||||
]);
|
||||
|
||||
function positiveSeconds(value: unknown, fallback: number): number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
export function connectionAttemptTimeoutMs(config: Pick<ConnectionConfig, "connect_timeout_secs" | "transport_layers"> & Partial<Pick<ConnectionConfig, "db_type">>): number {
|
||||
const timeouts = [positiveSeconds(config.connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT_SECS)];
|
||||
const baseTimeoutSecs = positiveSeconds(config.connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT_SECS);
|
||||
const timeouts = [AGENT_DRIVER_TYPES.has(config.db_type as DatabaseType) ? Math.max(baseTimeoutSecs, AGENT_DRIVER_MIN_CONNECT_TIMEOUT_SECS) : baseTimeoutSecs];
|
||||
for (const layer of config.transport_layers ?? []) {
|
||||
if (layer.type === "ssh") {
|
||||
timeouts.push(positiveSeconds(layer.connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT_SECS));
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
import type { ComposerTranslation } from "vue-i18n";
|
||||
import type { DatabaseType } from "@/types/database";
|
||||
|
||||
export type DocumentStoreKind = "mongodb" | "elasticsearch";
|
||||
export type DocumentFilterMode = "equals" | "not-equals" | "like" | "not-like" | "greater-than" | "less-than" | "is-null" | "is-not-null";
|
||||
|
||||
export type DocumentFilterRule = {
|
||||
id: string;
|
||||
fieldName: string;
|
||||
mode: DocumentFilterMode;
|
||||
rawValue: string;
|
||||
conjunction: "AND" | "OR";
|
||||
};
|
||||
|
||||
export type DocumentStoreQueryPreviewOptions = {
|
||||
collection: string;
|
||||
filterJson?: string;
|
||||
sortJson?: string;
|
||||
skip: number;
|
||||
limit: number;
|
||||
};
|
||||
|
||||
export type DocumentStoreProvider = {
|
||||
kind: DocumentStoreKind;
|
||||
filterInputLabel: string;
|
||||
sortInputLabel: string;
|
||||
documentsLabel(options: { total: number; t: ComposerTranslation }): string;
|
||||
queryPreview(options: DocumentStoreQueryPreviewOptions): string;
|
||||
sortInputForColumn(column: string, direction: "asc" | "desc" | null): string;
|
||||
};
|
||||
|
||||
export const documentFilterModeOptions: Array<{ value: DocumentFilterMode; labelKey: string }> = [
|
||||
{ value: "equals", labelKey: "grid.filterBuilderEquals" },
|
||||
{ value: "not-equals", labelKey: "grid.filterBuilderNotEquals" },
|
||||
{ value: "like", labelKey: "grid.filterBuilderContains" },
|
||||
{ value: "not-like", labelKey: "grid.filterBuilderNotContains" },
|
||||
{ value: "greater-than", labelKey: "grid.filterBuilderGreaterThan" },
|
||||
{ value: "less-than", labelKey: "grid.filterBuilderLessThan" },
|
||||
{ value: "is-null", labelKey: "grid.filterBuilderIsNull" },
|
||||
{ value: "is-not-null", labelKey: "grid.filterBuilderIsNotNull" },
|
||||
];
|
||||
|
||||
const mongoDocumentProvider: DocumentStoreProvider = {
|
||||
kind: "mongodb",
|
||||
filterInputLabel: "find",
|
||||
sortInputLabel: "sort",
|
||||
documentsLabel: ({ total, t }) => t("mongo.documents", { count: total }),
|
||||
queryPreview: ({ collection, filterJson, sortJson, skip, limit }) => {
|
||||
const parts = [`db.${collection}.find(${filterJson || "{}"})`];
|
||||
if (sortJson?.trim()) parts.push(`.sort(${sortJson.trim()})`);
|
||||
parts.push(`.skip(${skip}).limit(${limit})`);
|
||||
return parts.join("");
|
||||
},
|
||||
sortInputForColumn: (column, direction) => (direction ? JSON.stringify({ [column]: direction === "asc" ? 1 : -1 }) : ""),
|
||||
};
|
||||
|
||||
const elasticsearchDocumentProvider: DocumentStoreProvider = {
|
||||
kind: "elasticsearch",
|
||||
filterInputLabel: "filter",
|
||||
sortInputLabel: "sort",
|
||||
documentsLabel: () => "Documents",
|
||||
queryPreview: ({ collection, filterJson, sortJson, skip, limit }) => {
|
||||
const body = safeElasticsearchSearchBodyFromDocumentQuery({ filterJson, sortJson, skip, limit });
|
||||
return `POST /${collection}/_search\n${JSON.stringify(body, null, 2)}`;
|
||||
},
|
||||
sortInputForColumn: mongoDocumentProvider.sortInputForColumn,
|
||||
};
|
||||
|
||||
export function documentStoreProviderFor(databaseType?: DatabaseType): DocumentStoreProvider {
|
||||
return databaseType === "elasticsearch" ? elasticsearchDocumentProvider : mongoDocumentProvider;
|
||||
}
|
||||
|
||||
export function defaultDocumentFilterRule(id: string, fieldName = ""): DocumentFilterRule {
|
||||
return {
|
||||
id,
|
||||
fieldName,
|
||||
mode: "equals",
|
||||
rawValue: "",
|
||||
conjunction: "AND",
|
||||
};
|
||||
}
|
||||
|
||||
export function documentFilterModeNeedsValue(mode: DocumentFilterMode): boolean {
|
||||
return mode !== "is-null" && mode !== "is-not-null";
|
||||
}
|
||||
|
||||
export function buildDocumentFilterCondition(rule: DocumentFilterRule): Record<string, unknown> | null {
|
||||
if (!rule.fieldName) return null;
|
||||
if (documentFilterModeNeedsValue(rule.mode) && !rule.rawValue.trim()) return null;
|
||||
const value = documentFilterModeNeedsValue(rule.mode) ? parseDocumentFilterValue(rule.rawValue) : null;
|
||||
switch (rule.mode) {
|
||||
case "equals":
|
||||
return { [rule.fieldName]: value };
|
||||
case "not-equals":
|
||||
return { [rule.fieldName]: { $ne: value } };
|
||||
case "like":
|
||||
return { [rule.fieldName]: { $regex: String(value), $options: "i" } };
|
||||
case "not-like":
|
||||
return { [rule.fieldName]: { $not: { $regex: String(value), $options: "i" } } };
|
||||
case "greater-than":
|
||||
return { [rule.fieldName]: { $gt: value } };
|
||||
case "less-than":
|
||||
return { [rule.fieldName]: { $lt: value } };
|
||||
case "is-null":
|
||||
return { [rule.fieldName]: null };
|
||||
case "is-not-null":
|
||||
return { [rule.fieldName]: { $ne: null } };
|
||||
}
|
||||
}
|
||||
|
||||
export function combineDocumentFilterConditions(conditions: Record<string, unknown>[], rules: Pick<DocumentFilterRule, "conjunction">[]): Record<string, unknown> | null {
|
||||
if (conditions.length === 0) return null;
|
||||
let result = conditions[0];
|
||||
for (let i = 1; i < conditions.length; i++) {
|
||||
const operator = rules[i]?.conjunction === "OR" ? "$or" : "$and";
|
||||
result = { [operator]: [result, conditions[i]] };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function parseDocumentFilterInput(input: string): Record<string, unknown> {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed) return {};
|
||||
const parsed = JSON.parse(trimmed);
|
||||
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};
|
||||
}
|
||||
|
||||
export function currentDocumentFilterJson(input: string, structured: Record<string, unknown> | null): string | undefined {
|
||||
const manual = parseDocumentFilterInput(input);
|
||||
const filter = structured ? (Object.keys(manual).length ? { $and: [manual, structured] } : structured) : manual;
|
||||
return Object.keys(filter).length ? JSON.stringify(filter) : undefined;
|
||||
}
|
||||
|
||||
function parseDocumentFilterValue(raw: string): unknown {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return "";
|
||||
try {
|
||||
return JSON.parse(trimmed);
|
||||
} catch {
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
|
||||
export function elasticsearchSearchBodyFromDocumentQuery(options: Pick<DocumentStoreQueryPreviewOptions, "filterJson" | "sortJson" | "skip" | "limit">): Record<string, unknown> {
|
||||
const body: Record<string, unknown> = {
|
||||
from: options.skip,
|
||||
size: options.limit,
|
||||
};
|
||||
const query = elasticsearchQueryFromDocumentFilter(options.filterJson);
|
||||
if (query) body.query = query;
|
||||
body.sort = elasticsearchSortFromDocumentSort(options.sortJson);
|
||||
return body;
|
||||
}
|
||||
|
||||
function safeElasticsearchSearchBodyFromDocumentQuery(options: Pick<DocumentStoreQueryPreviewOptions, "filterJson" | "sortJson" | "skip" | "limit">): Record<string, unknown> {
|
||||
try {
|
||||
return elasticsearchSearchBodyFromDocumentQuery(options);
|
||||
} catch {
|
||||
return {
|
||||
from: options.skip,
|
||||
size: options.limit,
|
||||
sort: ["_doc"],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function elasticsearchQueryFromDocumentFilter(filterJson?: string): Record<string, unknown> | null {
|
||||
const trimmed = filterJson?.trim();
|
||||
if (!trimmed || trimmed === "{}") return null;
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (!isPlainRecord(parsed) || Object.keys(parsed).length === 0) return null;
|
||||
return translateDocumentFilterToElasticsearchQuery(parsed);
|
||||
}
|
||||
|
||||
function translateDocumentFilterToElasticsearchQuery(filter: Record<string, unknown>): Record<string, unknown> {
|
||||
const filters: Record<string, unknown>[] = [];
|
||||
for (const [key, value] of Object.entries(filter)) {
|
||||
if (key === "$and") {
|
||||
filters.push(...translateLogicalArrayToElasticsearch("$and", value));
|
||||
} else if (key === "$or") {
|
||||
const should = translateLogicalArrayToElasticsearch("$or", value);
|
||||
if (should.length > 0) filters.push({ bool: { should, minimum_should_match: 1 } });
|
||||
} else {
|
||||
filters.push(translateFieldFilterToElasticsearchQuery(key, value));
|
||||
}
|
||||
}
|
||||
if (filters.length === 1) return filters[0];
|
||||
return { bool: { filter: filters } };
|
||||
}
|
||||
|
||||
function translateLogicalArrayToElasticsearch(operator: "$and" | "$or", value: unknown): Record<string, unknown>[] {
|
||||
if (!Array.isArray(value)) throw new Error(`${operator} must be an array`);
|
||||
return value.filter(isPlainRecord).map(translateDocumentFilterToElasticsearchQuery);
|
||||
}
|
||||
|
||||
function translateFieldFilterToElasticsearchQuery(field: string, value: unknown): Record<string, unknown> {
|
||||
if (!isPlainRecord(value) || !Object.keys(value).some((key) => key.startsWith("$"))) {
|
||||
return termOrNullQuery(field, value);
|
||||
}
|
||||
|
||||
const filter: Record<string, unknown>[] = [];
|
||||
const mustNot: Record<string, unknown>[] = [];
|
||||
const range: Record<string, unknown> = {};
|
||||
for (const [operator, operatorValue] of Object.entries(value)) {
|
||||
if (operator === "$options") continue;
|
||||
if (operator === "$ne") {
|
||||
if (operatorValue === null) filter.push({ exists: { field } });
|
||||
else mustNot.push({ term: { [field]: operatorValue } });
|
||||
} else if (operator === "$gt" || operator === "$gte" || operator === "$lt" || operator === "$lte") {
|
||||
range[operator.slice(1)] = operatorValue;
|
||||
} else if (operator === "$regex") {
|
||||
filter.push(wildcardQuery(field, operatorValue, value.$options));
|
||||
} else if (operator === "$not") {
|
||||
if (isPlainRecord(operatorValue) && "$regex" in operatorValue) {
|
||||
mustNot.push(wildcardQuery(field, operatorValue.$regex, operatorValue.$options ?? value.$options));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Object.keys(range).length > 0) filter.push({ range: { [field]: range } });
|
||||
if (filter.length === 1 && mustNot.length === 0) return filter[0];
|
||||
if (filter.length === 0 && mustNot.length > 0) return { bool: { must_not: mustNot } };
|
||||
const bool: Record<string, unknown> = {};
|
||||
if (filter.length > 0) bool.filter = filter;
|
||||
if (mustNot.length > 0) bool.must_not = mustNot;
|
||||
return { bool };
|
||||
}
|
||||
|
||||
function termOrNullQuery(field: string, value: unknown): Record<string, unknown> {
|
||||
if (value === null) return { bool: { must_not: [{ exists: { field } }] } };
|
||||
return { term: { [field]: value } };
|
||||
}
|
||||
|
||||
function wildcardQuery(field: string, value: unknown, options: unknown): Record<string, unknown> {
|
||||
const pattern = String(value ?? "");
|
||||
const wildcard = pattern.startsWith("*") || pattern.endsWith("*") ? pattern : `*${pattern}*`;
|
||||
return {
|
||||
wildcard: {
|
||||
[field]: {
|
||||
value: wildcard,
|
||||
case_insensitive: typeof options === "string" && options.toLowerCase().includes("i"),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function elasticsearchSortFromDocumentSort(sortJson?: string): unknown[] {
|
||||
const trimmed = sortJson?.trim();
|
||||
if (!trimmed || trimmed === "{}") return ["_doc"];
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (!isPlainRecord(parsed)) return ["_doc"];
|
||||
return Object.entries(parsed).map(([field, direction]) => ({
|
||||
[field]: { order: direction === -1 || (typeof direction === "string" && direction.toLowerCase() === "desc") ? "desc" : "asc" },
|
||||
}));
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -356,10 +356,13 @@ export function buildSqlCompletionThemeRules(): CodeMirrorStyleSpec {
|
||||
boxShadow: "0 8px 18px rgb(0 0 0 / 0.14)",
|
||||
color: "var(--popover-foreground)",
|
||||
fontFamily: `var(${EDITOR_FONT_FAMILY_CSS_VAR}, var(--font-mono, monospace))`,
|
||||
maxWidth: "min(520px, calc(100vw - 24px))",
|
||||
maxWidth: "min(760px, calc(100vw - 24px))",
|
||||
minWidth: "min(280px, calc(100vw - 24px))",
|
||||
overflow: "hidden",
|
||||
overflowX: "auto",
|
||||
overflowY: "hidden",
|
||||
padding: "4px 0",
|
||||
scrollbarColor: colorMixValue("var(--muted-foreground) transparent", "color-mix(in oklch, var(--muted-foreground) 44%, transparent) transparent"),
|
||||
scrollbarWidth: "thin",
|
||||
zIndex: "9999",
|
||||
},
|
||||
".cm-tooltip.cm-tooltip-autocomplete *": {
|
||||
@@ -368,7 +371,9 @@ export function buildSqlCompletionThemeRules(): CodeMirrorStyleSpec {
|
||||
".cm-tooltip.cm-tooltip-autocomplete > ul": {
|
||||
maxHeight: "min(280px, calc(100vh - 32px))",
|
||||
minWidth: "min(280px, calc(100vw - 24px))",
|
||||
width: "max-content",
|
||||
overflowX: "hidden",
|
||||
overflowY: "auto",
|
||||
padding: "0 4px 0 !important",
|
||||
scrollbarColor: colorMixValue("var(--muted-foreground) transparent", "color-mix(in oklch, var(--muted-foreground) 44%, transparent) transparent"),
|
||||
scrollbarWidth: "thin",
|
||||
@@ -383,7 +388,6 @@ export function buildSqlCompletionThemeRules(): CodeMirrorStyleSpec {
|
||||
height: "28px",
|
||||
letterSpacing: "0",
|
||||
lineHeight: "28px",
|
||||
maxWidth: "100%",
|
||||
overflow: "hidden",
|
||||
padding: "0 10px !important",
|
||||
transition: "background-color 90ms ease, color 90ms ease",
|
||||
@@ -452,14 +456,11 @@ export function buildSqlCompletionThemeRules(): CodeMirrorStyleSpec {
|
||||
},
|
||||
".cm-completionLabel": {
|
||||
color: "inherit",
|
||||
flex: "0 1 auto",
|
||||
flex: "0 0 auto",
|
||||
fontFamily: `var(${EDITOR_FONT_FAMILY_CSS_VAR}, var(--font-mono, monospace))`,
|
||||
fontSize: `clamp(12px, var(${EDITOR_FONT_SIZE_CSS_VAR}, 13px), 14px)`,
|
||||
fontWeight: "520",
|
||||
letterSpacing: "0",
|
||||
minWidth: "0",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
},
|
||||
".cm-completionMatchedText": {
|
||||
@@ -472,12 +473,9 @@ export function buildSqlCompletionThemeRules(): CodeMirrorStyleSpec {
|
||||
fontSize: `clamp(11px, calc(var(${EDITOR_FONT_SIZE_CSS_VAR}, 13px) - 1px), 13px)`,
|
||||
fontWeight: "500",
|
||||
fontStyle: "normal",
|
||||
flex: "1 1 auto",
|
||||
flex: "0 0 auto",
|
||||
marginLeft: "10px",
|
||||
minWidth: "0",
|
||||
opacity: "1",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@ import type {
|
||||
DatabaseType,
|
||||
InstalledPlugin,
|
||||
JdbcDriverInfo,
|
||||
JdbcMavenBundleInfo,
|
||||
JdbcPluginStatus,
|
||||
SidebarLayout,
|
||||
SavedSqlFile,
|
||||
@@ -176,6 +177,10 @@ export async function listJdbcDrivers(): Promise<JdbcDriverInfo[]> {
|
||||
return get("/api/jdbc/drivers");
|
||||
}
|
||||
|
||||
export async function listJdbcMavenBundles(): Promise<JdbcMavenBundleInfo[]> {
|
||||
return get("/api/jdbc/drivers/maven");
|
||||
}
|
||||
|
||||
export async function importJdbcDrivers(pathsOrFiles: (string | File)[]): Promise<JdbcDriverInfo[]> {
|
||||
const formData = new FormData();
|
||||
for (const item of pathsOrFiles) {
|
||||
@@ -192,11 +197,19 @@ export async function importJdbcDrivers(pathsOrFiles: (string | File)[]): Promis
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function installJdbcDriverFromMaven(coordinate: string, repositories: string[] = []): Promise<JdbcDriverInfo[]> {
|
||||
return post("/api/jdbc/drivers/maven", { coordinate, repositories });
|
||||
}
|
||||
|
||||
export async function deleteJdbcDriver(path: string): Promise<JdbcDriverInfo[]> {
|
||||
const fileName = path.split("/").pop() || path;
|
||||
return del(`/api/jdbc/drivers/${encodeURIComponent(fileName)}`);
|
||||
}
|
||||
|
||||
export async function deleteJdbcMavenBundle(bundleId: string): Promise<JdbcDriverInfo[]> {
|
||||
return del(`/api/jdbc/drivers/maven/${encodeURIComponent(bundleId)}`);
|
||||
}
|
||||
|
||||
export async function jdbcPluginStatus(): Promise<JdbcPluginStatus> {
|
||||
return get("/api/jdbc/plugin/status");
|
||||
}
|
||||
@@ -1263,8 +1276,8 @@ export async function redisFlushDb(connectionId: string, db: number): Promise<vo
|
||||
return post("/api/redis/flush-db", { connectionId, db });
|
||||
}
|
||||
|
||||
export async function redisExecuteCommand(connectionId: string, db: number, command: string): Promise<RedisCommandResult> {
|
||||
return post("/api/redis/execute-command", { connectionId, db, command });
|
||||
export async function redisExecuteCommand(connectionId: string, db: number, command: string, skipSafetyCheck?: boolean): Promise<RedisCommandResult> {
|
||||
return post("/api/redis/execute-command", { connectionId, db, command, skipSafetyCheck: skipSafetyCheck ?? false });
|
||||
}
|
||||
|
||||
export async function redisLoadMore(connectionId: string, db: number, keyRaw: string, keyType: string, cursor: number, count: number): Promise<RedisValue> {
|
||||
@@ -1311,6 +1324,10 @@ export async function mongoFindDocuments(connectionId: string, database: string,
|
||||
return post("/api/mongo/find-documents", { connectionId, database, collection, skip, limit, filter, sort });
|
||||
}
|
||||
|
||||
export async function documentFindDocuments(connectionId: string, database: string, collection: string, skip: number, limit: number, filter?: string, sort?: string): Promise<MongoDocumentResult> {
|
||||
return post("/api/document-store/find-documents", { connectionId, database, collection, skip, limit, filter, sort });
|
||||
}
|
||||
|
||||
export async function mongoAggregateDocuments(connectionId: string, database: string, collection: string, pipelineJson: string, maxRows?: number): Promise<MongoDocumentResult> {
|
||||
return post("/api/mongo/aggregate-documents", { connectionId, database, collection, pipelineJson, maxRows });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { QueryResult } from "@/types/database";
|
||||
import { formatRedisCommandResult } from "@/lib/redisValuePresentation";
|
||||
|
||||
const KEY_VALUE_COMMANDS = new Set(["HGETALL"]);
|
||||
|
||||
function isKeyValueCommand(command: string): boolean {
|
||||
return KEY_VALUE_COMMANDS.has(command.toUpperCase().trim());
|
||||
}
|
||||
|
||||
export function redisCommandResultToQueryResult(value: unknown, elapsedMs: number, command?: string): QueryResult {
|
||||
if (Array.isArray(value) && command && isKeyValueCommand(command)) {
|
||||
const rows: (string | number | boolean | null)[][] = [];
|
||||
for (let i = 0; i + 1 < value.length; i += 2) {
|
||||
rows.push([formatRedisCommandResult(value[i]), formatRedisCommandResult(value[i + 1])]);
|
||||
}
|
||||
return {
|
||||
columns: ["field", "value"],
|
||||
rows,
|
||||
affected_rows: value.length / 2,
|
||||
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
|
||||
};
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
const rows: (string | number | boolean | null)[][] = value.map((item, i) => [i + 1, formatRedisCommandResult(item)]);
|
||||
return {
|
||||
columns: ["(index)", "value"],
|
||||
rows,
|
||||
affected_rows: value.length,
|
||||
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
|
||||
};
|
||||
}
|
||||
return {
|
||||
columns: ["result"],
|
||||
rows: [[formatRedisCommandResult(value)]],
|
||||
affected_rows: 0,
|
||||
execution_time_ms: Math.max(0, Math.round(elapsedMs)),
|
||||
};
|
||||
}
|
||||
@@ -5,6 +5,26 @@ export function emptyLayout(): SidebarLayout {
|
||||
return { groups: [], order: [] };
|
||||
}
|
||||
|
||||
function entryChildren(entry: Extract<SidebarOrderEntry, { type: "group" }>): SidebarOrderEntry[] {
|
||||
return entry.children ?? entry.connectionIds?.map((id) => ({ type: "connection" as const, id })) ?? [];
|
||||
}
|
||||
|
||||
function normalizeEntry(entry: SidebarOrderEntry, validIds: Set<string>, validGroups: Set<string>, seenConnections: Set<string>, seenGroups: Set<string>): SidebarOrderEntry | null {
|
||||
if (entry.type === "connection") {
|
||||
if (!validIds.has(entry.id) || seenConnections.has(entry.id)) return null;
|
||||
seenConnections.add(entry.id);
|
||||
return { type: "connection", id: entry.id };
|
||||
}
|
||||
|
||||
if (!validGroups.has(entry.id) || seenGroups.has(entry.id)) return null;
|
||||
seenGroups.add(entry.id);
|
||||
|
||||
const children = entryChildren(entry)
|
||||
.map((child) => normalizeEntry(child, validIds, validGroups, seenConnections, seenGroups))
|
||||
.filter(Boolean) as SidebarOrderEntry[];
|
||||
return { type: "group", id: entry.id, children };
|
||||
}
|
||||
|
||||
export function reconcileLayout(connectionIds: string[], layout: SidebarLayout | null): SidebarLayout {
|
||||
if (!layout) {
|
||||
return {
|
||||
@@ -14,34 +34,28 @@ export function reconcileLayout(connectionIds: string[], layout: SidebarLayout |
|
||||
}
|
||||
|
||||
const validIds = new Set(connectionIds);
|
||||
const seen = new Set<string>();
|
||||
|
||||
const order: SidebarOrderEntry[] = [];
|
||||
for (const entry of layout.order) {
|
||||
if (entry.type === "group") {
|
||||
const filtered = entry.connectionIds.filter((id) => {
|
||||
if (!validIds.has(id) || seen.has(id)) return false;
|
||||
seen.add(id);
|
||||
return true;
|
||||
});
|
||||
order.push({ type: "group", id: entry.id, connectionIds: filtered });
|
||||
} else {
|
||||
if (validIds.has(entry.id) && !seen.has(entry.id)) {
|
||||
seen.add(entry.id);
|
||||
order.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
const validGroups = new Set(layout.groups.map((group) => group.id));
|
||||
const seenConnections = new Set<string>();
|
||||
const seenGroups = new Set<string>();
|
||||
const order = layout.order.map((entry) => normalizeEntry(entry, validIds, validGroups, seenConnections, seenGroups)).filter(Boolean) as SidebarOrderEntry[];
|
||||
|
||||
for (const id of connectionIds) {
|
||||
if (!seen.has(id)) {
|
||||
if (!seenConnections.has(id)) {
|
||||
order.push({ type: "connection", id });
|
||||
}
|
||||
}
|
||||
|
||||
const usedGroupIds = new Set(order.filter((e) => e.type === "group").map((e) => e.id));
|
||||
const groups = layout.groups.filter((g) => usedGroupIds.has(g.id));
|
||||
const usedGroupIds = new Set<string>();
|
||||
const collectGroups = (entries: SidebarOrderEntry[]) => {
|
||||
for (const entry of entries) {
|
||||
if (entry.type !== "group") continue;
|
||||
usedGroupIds.add(entry.id);
|
||||
collectGroups(entryChildren(entry));
|
||||
}
|
||||
};
|
||||
collectGroups(order);
|
||||
|
||||
const groups = layout.groups.filter((group) => usedGroupIds.has(group.id));
|
||||
return { groups, order };
|
||||
}
|
||||
|
||||
@@ -68,75 +82,110 @@ function orderPinnedFirst(nodes: TreeNode[]): TreeNode[] {
|
||||
}
|
||||
|
||||
export function buildTreeNodesFromLayout(layout: SidebarLayout, connections: ConnectionConfig[], pinnedIds: Set<string>): TreeNode[] {
|
||||
const configMap = new Map(connections.map((c) => [c.id, c]));
|
||||
const groupMap = new Map(layout.groups.map((g) => [g.id, g]));
|
||||
const configMap = new Map(connections.map((connection) => [connection.id, connection]));
|
||||
const groupMap = new Map(layout.groups.map((group) => [group.id, group]));
|
||||
|
||||
const build = (entries: SidebarOrderEntry[]): TreeNode[] => {
|
||||
const nodes: TreeNode[] = [];
|
||||
for (const entry of entries) {
|
||||
if (entry.type === "connection") {
|
||||
const config = configMap.get(entry.id);
|
||||
if (config) nodes.push(makeConnectionNode(config, pinnedIds.has(entry.id)));
|
||||
continue;
|
||||
}
|
||||
|
||||
const nodes: TreeNode[] = [];
|
||||
for (const entry of layout.order) {
|
||||
if (entry.type === "group") {
|
||||
const group = groupMap.get(entry.id);
|
||||
if (!group) continue;
|
||||
const children: TreeNode[] = [];
|
||||
for (const connId of entry.connectionIds) {
|
||||
const config = configMap.get(connId);
|
||||
if (config) children.push(makeConnectionNode(config, pinnedIds.has(connId)));
|
||||
}
|
||||
nodes.push({
|
||||
id: group.id,
|
||||
label: group.name,
|
||||
type: "connection-group",
|
||||
isExpanded: !group.collapsed,
|
||||
children: orderPinnedFirst(children),
|
||||
children: orderPinnedFirst(build(entryChildren(entry))),
|
||||
});
|
||||
} else {
|
||||
const config = configMap.get(entry.id);
|
||||
if (config) nodes.push(makeConnectionNode(config, pinnedIds.has(entry.id)));
|
||||
}
|
||||
}
|
||||
return nodes;
|
||||
};
|
||||
|
||||
return orderPinnedFirst(nodes);
|
||||
return orderPinnedFirst(build(layout.order));
|
||||
}
|
||||
|
||||
export function findConnectionLocation(layout: SidebarLayout, connectionId: string): { entryIndex: number; groupId?: string; innerIndex?: number } | null {
|
||||
for (let i = 0; i < layout.order.length; i++) {
|
||||
const entry = layout.order[i];
|
||||
if (entry.type === "connection" && entry.id === connectionId) {
|
||||
return { entryIndex: i };
|
||||
export function findConnectionLocation(layout: SidebarLayout, connectionId: string): { entries: SidebarOrderEntry[]; entryIndex: number; groupId?: string } | null {
|
||||
const visit = (entries: SidebarOrderEntry[], groupId?: string): { entries: SidebarOrderEntry[]; entryIndex: number; groupId?: string } | null => {
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const entry = entries[i];
|
||||
if (entry.type === "connection" && entry.id === connectionId) return { entries, entryIndex: i, groupId };
|
||||
if (entry.type === "group") {
|
||||
const found = visit(entryChildren(entry), entry.id);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
return visit(layout.order);
|
||||
}
|
||||
|
||||
function findGroupEntry(entries: SidebarOrderEntry[], groupId: string): Extract<SidebarOrderEntry, { type: "group" }> | null {
|
||||
for (const entry of entries) {
|
||||
if (entry.type !== "group") continue;
|
||||
if (entry.id === groupId) return entry;
|
||||
const found = findGroupEntry(entryChildren(entry), groupId);
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function cloneEntries(entries: SidebarOrderEntry[]): SidebarOrderEntry[] {
|
||||
return entries.map((entry) => (entry.type === "group" ? { type: "group", id: entry.id, children: cloneEntries(entryChildren(entry)) } : { ...entry }));
|
||||
}
|
||||
|
||||
function removeEntry(entries: SidebarOrderEntry[], id: string): SidebarOrderEntry | null {
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const entry = entries[i];
|
||||
if ((entry.type === "connection" && entry.id === id) || (entry.type === "group" && entry.id === id)) {
|
||||
entries.splice(i, 1);
|
||||
return entry;
|
||||
}
|
||||
if (entry.type === "group") {
|
||||
const innerIndex = entry.connectionIds.indexOf(connectionId);
|
||||
if (innerIndex >= 0) {
|
||||
return { entryIndex: i, groupId: entry.id, innerIndex };
|
||||
}
|
||||
const removed = removeEntry(entry.children ?? [], id);
|
||||
if (removed) return removed;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function removeConnectionFromLayout(order: SidebarOrderEntry[], connectionId: string): SidebarOrderEntry[] {
|
||||
return order
|
||||
.map((entry) => {
|
||||
if (entry.type === "connection" && entry.id === connectionId) return null;
|
||||
if (entry.type === "group") {
|
||||
return { ...entry, connectionIds: entry.connectionIds.filter((id) => id !== connectionId) };
|
||||
}
|
||||
return entry;
|
||||
})
|
||||
.filter(Boolean) as SidebarOrderEntry[];
|
||||
function removeConnectionFromEntries(entries: SidebarOrderEntry[], connectionId: string): SidebarOrderEntry[] {
|
||||
const next = cloneEntries(entries);
|
||||
removeEntry(next, connectionId);
|
||||
return next;
|
||||
}
|
||||
|
||||
function containsGroup(entry: SidebarOrderEntry, groupId: string): boolean {
|
||||
if (entry.type !== "group") return false;
|
||||
if (entry.id === groupId) return true;
|
||||
return entryChildren(entry).some((child) => containsGroup(child, groupId));
|
||||
}
|
||||
|
||||
function expandGroup(layout: SidebarLayout, groupId: string): SidebarLayout {
|
||||
return {
|
||||
...layout,
|
||||
groups: layout.groups.map((group) => (group.id === groupId ? { ...group, collapsed: false } : group)),
|
||||
};
|
||||
}
|
||||
|
||||
export function moveConnectionToGroup(layout: SidebarLayout, connectionId: string, targetGroupId: string | null): SidebarLayout {
|
||||
const order = removeConnectionFromLayout([...layout.order], connectionId);
|
||||
const order = removeConnectionFromEntries(layout.order, connectionId);
|
||||
const entry: SidebarOrderEntry = { type: "connection", id: connectionId };
|
||||
|
||||
if (targetGroupId) {
|
||||
const groupEntry = order.find((e) => e.type === "group" && e.id === targetGroupId);
|
||||
if (groupEntry && groupEntry.type === "group") {
|
||||
groupEntry.connectionIds.push(connectionId);
|
||||
const group = findGroupEntry(order, targetGroupId);
|
||||
if (group) {
|
||||
group.children = [...(group.children ?? []), entry];
|
||||
return { ...expandGroup(layout, targetGroupId), order };
|
||||
}
|
||||
} else {
|
||||
order.push({ type: "connection", id: connectionId });
|
||||
}
|
||||
|
||||
order.push(entry);
|
||||
return { ...layout, order };
|
||||
}
|
||||
|
||||
@@ -145,75 +194,58 @@ export type DropPosition = "before" | "after" | "inside";
|
||||
export function reorderEntry(layout: SidebarLayout, draggedId: string, targetId: string, position: DropPosition): SidebarLayout {
|
||||
if (draggedId === targetId) return layout;
|
||||
|
||||
const isDraggedGroup = layout.order.some((e) => e.type === "group" && e.id === draggedId);
|
||||
const isTargetGroup = layout.order.some((e) => e.type === "group" && e.id === targetId);
|
||||
const order = cloneEntries(layout.order);
|
||||
const dragged = removeEntry(order, draggedId);
|
||||
if (!dragged) return layout;
|
||||
|
||||
if (isDraggedGroup) {
|
||||
return reorderGroup(layout, draggedId, targetId, position);
|
||||
}
|
||||
if (dragged.type === "group" && containsGroup(dragged, targetId)) return layout;
|
||||
|
||||
if (position === "inside" && isTargetGroup) {
|
||||
return moveConnectionToGroup(layout, draggedId, targetId);
|
||||
}
|
||||
|
||||
return reorderConnection(layout, draggedId, targetId, position);
|
||||
}
|
||||
|
||||
function reorderGroup(layout: SidebarLayout, draggedId: string, targetId: string, position: DropPosition): SidebarLayout {
|
||||
const order = [...layout.order];
|
||||
const draggedIndex = order.findIndex((e) => e.type === "group" && e.id === draggedId);
|
||||
if (draggedIndex < 0) return layout;
|
||||
|
||||
const [dragged] = order.splice(draggedIndex, 1);
|
||||
|
||||
let targetIndex = order.findIndex((e) => (e.type === "group" && e.id === targetId) || (e.type === "connection" && e.id === targetId));
|
||||
if (targetIndex < 0) {
|
||||
order.push(dragged);
|
||||
} else {
|
||||
if (position === "after") targetIndex++;
|
||||
order.splice(targetIndex, 0, dragged);
|
||||
}
|
||||
|
||||
return { ...layout, order };
|
||||
}
|
||||
|
||||
function reorderConnection(layout: SidebarLayout, draggedId: string, targetId: string, position: DropPosition): SidebarLayout {
|
||||
const order = removeConnectionFromLayout([...layout.order], draggedId);
|
||||
|
||||
const targetLoc = findConnectionLocation({ ...layout, order }, targetId);
|
||||
if (!targetLoc) {
|
||||
order.push({ type: "connection", id: draggedId });
|
||||
return { ...layout, order };
|
||||
}
|
||||
|
||||
if (targetLoc.groupId) {
|
||||
const groupEntry = order[targetLoc.entryIndex];
|
||||
if (groupEntry.type === "group") {
|
||||
const insertAt = position === "after" ? targetLoc.innerIndex! + 1 : targetLoc.innerIndex!;
|
||||
groupEntry.connectionIds.splice(insertAt, 0, draggedId);
|
||||
}
|
||||
} else {
|
||||
const isTargetGroup = order[targetLoc.entryIndex]?.type === "group";
|
||||
if (isTargetGroup && position === "inside") {
|
||||
const entry = order[targetLoc.entryIndex];
|
||||
if (entry.type === "group") entry.connectionIds.push(draggedId);
|
||||
} else {
|
||||
const insertAt = position === "after" ? targetLoc.entryIndex + 1 : targetLoc.entryIndex;
|
||||
order.splice(insertAt, 0, { type: "connection", id: draggedId });
|
||||
if (position === "inside") {
|
||||
const targetGroup = findGroupEntry(order, targetId);
|
||||
if (targetGroup) {
|
||||
targetGroup.children = [...(targetGroup.children ?? []), dragged];
|
||||
return { ...layout, order };
|
||||
}
|
||||
}
|
||||
|
||||
const insertNear = (entries: SidebarOrderEntry[]): boolean => {
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const entry = entries[i];
|
||||
if ((entry.type === "connection" && entry.id === targetId) || (entry.type === "group" && entry.id === targetId)) {
|
||||
entries.splice(position === "after" ? i + 1 : i, 0, dragged);
|
||||
return true;
|
||||
}
|
||||
if (entry.type === "group" && insertNear(entry.children ?? [])) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
if (!insertNear(order)) order.push(dragged);
|
||||
return { ...layout, order };
|
||||
}
|
||||
|
||||
export function createGroup(layout: SidebarLayout, name: string): { layout: SidebarLayout; groupId: string } {
|
||||
export function createGroup(layout: SidebarLayout, name: string, parentGroupId?: string | null): { layout: SidebarLayout; groupId: string } {
|
||||
const groupId = uuid();
|
||||
const group: ConnectionGroup = { id: groupId, name, collapsed: false };
|
||||
const order = cloneEntries(layout.order);
|
||||
const entry: SidebarOrderEntry = { type: "group", id: groupId, children: [] };
|
||||
|
||||
if (parentGroupId) {
|
||||
const parent = findGroupEntry(order, parentGroupId);
|
||||
if (parent) {
|
||||
parent.children = [...(parent.children ?? []), entry];
|
||||
} else {
|
||||
order.push(entry);
|
||||
}
|
||||
} else {
|
||||
order.push(entry);
|
||||
}
|
||||
|
||||
return {
|
||||
groupId,
|
||||
layout: {
|
||||
groups: [...layout.groups, group],
|
||||
order: [...layout.order, { type: "group" as const, id: groupId, connectionIds: [] }],
|
||||
order,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -221,23 +253,30 @@ export function createGroup(layout: SidebarLayout, name: string): { layout: Side
|
||||
export function renameGroup(layout: SidebarLayout, groupId: string, name: string): SidebarLayout {
|
||||
return {
|
||||
...layout,
|
||||
groups: layout.groups.map((g) => (g.id === groupId ? { ...g, name } : g)),
|
||||
groups: layout.groups.map((group) => (group.id === groupId ? { ...group, name } : group)),
|
||||
};
|
||||
}
|
||||
|
||||
export function deleteGroup(layout: SidebarLayout, groupId: string): SidebarLayout {
|
||||
const order: SidebarOrderEntry[] = [];
|
||||
for (const entry of layout.order) {
|
||||
if (entry.type === "group" && entry.id === groupId) {
|
||||
for (const connId of entry.connectionIds) {
|
||||
order.push({ type: "connection", id: connId });
|
||||
const order = cloneEntries(layout.order);
|
||||
const removeGroup = (entries: SidebarOrderEntry[]): boolean => {
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const entry = entries[i];
|
||||
if (entry.type === "group" && entry.id === groupId) {
|
||||
entries.splice(i, 1, ...entryChildren(entry));
|
||||
return true;
|
||||
}
|
||||
if (entry.type === "group") {
|
||||
const removed = removeGroup(entry.children ?? []);
|
||||
if (removed) return true;
|
||||
}
|
||||
} else {
|
||||
order.push(entry);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const removed = removeGroup(order);
|
||||
return {
|
||||
groups: layout.groups.filter((g) => g.id !== groupId),
|
||||
groups: removed ? layout.groups.filter((group) => group.id !== groupId) : layout.groups,
|
||||
order,
|
||||
};
|
||||
}
|
||||
@@ -245,21 +284,14 @@ export function deleteGroup(layout: SidebarLayout, groupId: string): SidebarLayo
|
||||
export function toggleGroupCollapsed(layout: SidebarLayout, groupId: string): SidebarLayout {
|
||||
return {
|
||||
...layout,
|
||||
groups: layout.groups.map((g) => (g.id === groupId ? { ...g, collapsed: !g.collapsed } : g)),
|
||||
groups: layout.groups.map((group) => (group.id === groupId ? { ...group, collapsed: !group.collapsed } : group)),
|
||||
};
|
||||
}
|
||||
|
||||
export function removeConnectionFromSidebarLayout(layout: SidebarLayout, connectionId: string): SidebarLayout {
|
||||
return { ...layout, order: removeConnectionFromLayout(layout.order, connectionId) };
|
||||
return { ...layout, order: removeConnectionFromEntries(layout.order, connectionId) };
|
||||
}
|
||||
|
||||
export function appendConnectionToLayout(layout: SidebarLayout, connectionId: string, groupId?: string | null): SidebarLayout {
|
||||
if (groupId && layout.groups.some((group) => group.id === groupId)) {
|
||||
return {
|
||||
...layout,
|
||||
groups: layout.groups.map((group) => (group.id === groupId ? { ...group, collapsed: false } : group)),
|
||||
order: layout.order.map((entry) => (entry.type === "group" && entry.id === groupId ? { ...entry, connectionIds: [...entry.connectionIds, connectionId] } : entry)),
|
||||
};
|
||||
}
|
||||
return { ...layout, order: [...layout.order, { type: "connection" as const, id: connectionId }] };
|
||||
return moveConnectionToGroup(layout, connectionId, groupId ?? null);
|
||||
}
|
||||
|
||||
@@ -1041,6 +1041,7 @@ export function buildSqlCompletionItemsFromContext(
|
||||
}
|
||||
|
||||
export function shouldAutoOpenSqlCompletion(sql: string, cursor: number): boolean {
|
||||
if (isSqlCommentContext(sql, cursor)) return false;
|
||||
const previousChar = sql[cursor - 1];
|
||||
if (!previousChar) return false;
|
||||
if (/\bon\s+$/i.test(sql.slice(0, cursor))) return true;
|
||||
@@ -1053,6 +1054,82 @@ export function shouldAutoOpenSqlCompletion(sql: string, cursor: number): boolea
|
||||
return /[\w$.@]/.test(previousChar);
|
||||
}
|
||||
|
||||
export function isSqlCommentContext(sql: string, cursor: number): boolean {
|
||||
const end = Math.max(0, Math.min(cursor, sql.length));
|
||||
let inSingleQuote = false;
|
||||
let inDoubleQuote = false;
|
||||
let inBacktick = false;
|
||||
let inBracket = false;
|
||||
let inLineComment = false;
|
||||
let inBlockComment = false;
|
||||
|
||||
for (let index = 0; index < end; index += 1) {
|
||||
const ch = sql[index] ?? "";
|
||||
const next = sql[index + 1] ?? "";
|
||||
|
||||
if (inLineComment) {
|
||||
if (ch === "\n" || ch === "\r") inLineComment = false;
|
||||
continue;
|
||||
}
|
||||
if (inBlockComment) {
|
||||
if (ch === "*" && next === "/") {
|
||||
inBlockComment = false;
|
||||
index += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inSingleQuote) {
|
||||
if (ch === "\\" && next) {
|
||||
index += 1;
|
||||
} else if (ch === "'" && next === "'") {
|
||||
index += 1;
|
||||
} else if (ch === "'") {
|
||||
inSingleQuote = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (inDoubleQuote) {
|
||||
if (ch === "\\" && next) {
|
||||
index += 1;
|
||||
} else if (ch === '"' && next === '"') {
|
||||
index += 1;
|
||||
} else if (ch === '"') {
|
||||
inDoubleQuote = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (inBacktick) {
|
||||
if (ch === "`") inBacktick = false;
|
||||
continue;
|
||||
}
|
||||
if (inBracket) {
|
||||
if (ch === "]") inBracket = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "-" && next === "-") {
|
||||
inLineComment = true;
|
||||
index += 1;
|
||||
} else if (ch === "#") {
|
||||
inLineComment = true;
|
||||
} else if (ch === "/" && next === "*") {
|
||||
inBlockComment = true;
|
||||
index += 1;
|
||||
} else if (ch === "'") {
|
||||
inSingleQuote = true;
|
||||
} else if (ch === '"') {
|
||||
inDoubleQuote = true;
|
||||
} else if (ch === "`") {
|
||||
inBacktick = true;
|
||||
} else if (ch === "[") {
|
||||
inBracket = true;
|
||||
}
|
||||
}
|
||||
|
||||
return inLineComment || inBlockComment;
|
||||
}
|
||||
|
||||
export function isSqlLikeCompletionStatement(sql: string, cursor: number): boolean {
|
||||
const statement = extractStatementAt(sql, cursor).trimStart();
|
||||
if (/^(select|with)\b/i.test(statement)) return true;
|
||||
|
||||
@@ -80,7 +80,7 @@ export function areSqlSemanticDiagnosticsEqual(left: readonly SqlSemanticDiagnos
|
||||
}
|
||||
|
||||
export function shouldRunSqlSemanticDiagnostics(sql: string, cursor: number, options: { databaseType?: DatabaseType } = {}): boolean {
|
||||
if (options.databaseType === "mongodb" || options.databaseType === "elasticsearch") return false;
|
||||
if (options.databaseType === "mongodb" || options.databaseType === "elasticsearch" || options.databaseType === "redis") return false;
|
||||
const context = getSqlCompletionContext(sql, cursor);
|
||||
if (context.suggestTables || context.exclusiveTableSuggestions || context.exclusiveColumnSuggestions) return false;
|
||||
if (context.qualifier) return false;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useConnectionStore } from "@/stores/connectionStore";
|
||||
import { useSettingsStore } from "@/stores/settingsStore";
|
||||
import type { QueryResult, QueryTab } from "@/types/database";
|
||||
import type { ConnectionConfig, QueryResult, QueryTab } from "@/types/database";
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||
|
||||
@@ -19,10 +19,22 @@ export function isConnectionReadonly(connectionId: string): boolean {
|
||||
return connectionStore.getConfig(connectionId)?.read_only ?? false;
|
||||
}
|
||||
|
||||
function jdbcTargetLabel(connection: ConnectionConfig): string {
|
||||
const url = connection.connection_string?.trim() || "";
|
||||
const serviceMatch = url.match(/@\/\/[^/?;]+\/([^?;]+)/);
|
||||
if (serviceMatch?.[1]) return serviceMatch[1];
|
||||
const sidMatch = url.match(/@[^:]+:\d+:([^?;]+)/);
|
||||
if (sidMatch?.[1]) return sidMatch[1];
|
||||
const pathMatch = url.match(/^jdbc:[^:]+:\/\/[^/?;]+\/([^?;]+)/);
|
||||
if (pathMatch?.[1]) return pathMatch[1];
|
||||
return connection.driver_label || "JDBC";
|
||||
}
|
||||
|
||||
export function databaseDisplayNameForTab(connectionId: string, database: string, t: Translate): string {
|
||||
const connectionStore = useConnectionStore();
|
||||
const connection = connectionStore.getConfig(connectionId);
|
||||
if (connection?.db_type === "redis" && database !== "") return `db${database}`;
|
||||
if (connection?.db_type === "jdbc" && !database) return jdbcTargetLabel(connection);
|
||||
return database || t("editor.noDatabase");
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ export interface EditableStructureIndex {
|
||||
id: string;
|
||||
name: string;
|
||||
columns: string[];
|
||||
nameEdited?: boolean;
|
||||
isUnique: boolean;
|
||||
isPrimary: boolean;
|
||||
filter: string;
|
||||
|
||||
@@ -4,11 +4,17 @@ import type { ColumnExtra, EditableStructureColumn, EditableStructureIndex } fro
|
||||
export const DATA_TYPE_OPTIONS: Record<string, string[]> = {
|
||||
mysql: [
|
||||
"tinyint",
|
||||
"tinyint unsigned",
|
||||
"smallint",
|
||||
"smallint unsigned",
|
||||
"mediumint",
|
||||
"mediumint unsigned",
|
||||
"int",
|
||||
"int unsigned",
|
||||
"integer",
|
||||
"integer unsigned",
|
||||
"bigint",
|
||||
"bigint unsigned",
|
||||
"float",
|
||||
"double",
|
||||
"double precision",
|
||||
@@ -256,12 +262,18 @@ export function getDataTypeOptions(dbType: DatabaseType | undefined): string[] {
|
||||
|
||||
export const DEFAULT_TYPE_LENGTHS: Record<string, string> = {
|
||||
tinyint: "4",
|
||||
"tinyint unsigned": "4",
|
||||
smallint: "6",
|
||||
"smallint unsigned": "6",
|
||||
mediumint: "9",
|
||||
"mediumint unsigned": "9",
|
||||
int: "11",
|
||||
"int unsigned": "11",
|
||||
integer: "11",
|
||||
"integer unsigned": "11",
|
||||
int4: "11",
|
||||
bigint: "20",
|
||||
"bigint unsigned": "20",
|
||||
int8: "20",
|
||||
float: "10,2",
|
||||
real: "10,2",
|
||||
@@ -346,6 +358,7 @@ export function createIndexDrafts(indexes: IndexInfo[]): EditableStructureIndex[
|
||||
id: `existing:${index.name}`,
|
||||
name: index.name,
|
||||
columns: [...index.columns],
|
||||
nameEdited: true,
|
||||
isUnique: index.is_unique,
|
||||
isPrimary: index.is_primary,
|
||||
filter: index.filter ?? "",
|
||||
@@ -361,6 +374,48 @@ export function toColumnNames(columns: string[]): string {
|
||||
return columns.join(", ");
|
||||
}
|
||||
|
||||
const AUTO_INDEX_NAME_MAX_LENGTH = 63;
|
||||
|
||||
function normalizeIndexNamePart(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
const unquoted = (trimmed.startsWith("[") && trimmed.endsWith("]")) || (trimmed.startsWith("`") && trimmed.endsWith("`")) || (trimmed.startsWith('"') && trimmed.endsWith('"')) ? trimmed.slice(1, -1) : trimmed;
|
||||
return unquoted
|
||||
.trim()
|
||||
.replace(/[^a-zA-Z0-9]+/g, "_")
|
||||
.replace(/_+/g, "_")
|
||||
.replace(/^_+|_+$/g, "")
|
||||
.toUpperCase();
|
||||
}
|
||||
|
||||
function truncateIndexName(value: string, maxLength = AUTO_INDEX_NAME_MAX_LENGTH): string {
|
||||
if (value.length <= maxLength) return value;
|
||||
const suffix = "_IDX";
|
||||
if (!value.endsWith(suffix)) return value.slice(0, maxLength).replace(/_+$/g, "");
|
||||
return `${value.slice(0, maxLength - suffix.length).replace(/_+$/g, "")}${suffix}`;
|
||||
}
|
||||
|
||||
export function generateIndexName(tableName: string, columns: string[], maxLength = AUTO_INDEX_NAME_MAX_LENGTH): string {
|
||||
const parts = [tableName, ...columns].map(normalizeIndexNamePart).filter(Boolean);
|
||||
if (parts.length === 0) return "";
|
||||
return truncateIndexName(`${parts.join("_")}_IDX`, maxLength);
|
||||
}
|
||||
|
||||
export function generateUniqueIndexName(tableName: string, columns: string[], existingNames: Iterable<string>, maxLength = AUTO_INDEX_NAME_MAX_LENGTH): string {
|
||||
const base = generateIndexName(tableName, columns, maxLength);
|
||||
if (!base) return "";
|
||||
|
||||
const taken = new Set([...existingNames].map((name) => name.trim().toLowerCase()).filter(Boolean));
|
||||
if (!taken.has(base.toLowerCase())) return base;
|
||||
|
||||
for (let counter = 2; counter < 10_000; counter++) {
|
||||
const suffix = `_${counter}`;
|
||||
const stem = base.length + suffix.length <= maxLength ? base : base.slice(0, maxLength - suffix.length).replace(/_+$/g, "");
|
||||
const candidate = `${stem}${suffix}`;
|
||||
if (!taken.has(candidate.toLowerCase())) return candidate;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
export function splitDataType(raw: string): { baseType: string; params: string } {
|
||||
const trimmed = raw.trim();
|
||||
const parenIdx = trimmed.indexOf("(");
|
||||
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
DatabaseType,
|
||||
InstalledPlugin,
|
||||
JdbcDriverInfo,
|
||||
JdbcMavenBundleInfo,
|
||||
JdbcPluginStatus,
|
||||
SavedSqlFile,
|
||||
SavedSqlFolder,
|
||||
@@ -782,6 +783,10 @@ export async function listJdbcDrivers(): Promise<JdbcDriverInfo[]> {
|
||||
return invoke("list_jdbc_drivers");
|
||||
}
|
||||
|
||||
export async function listJdbcMavenBundles(): Promise<JdbcMavenBundleInfo[]> {
|
||||
return invoke("list_jdbc_maven_bundles");
|
||||
}
|
||||
|
||||
export async function importJdbcDrivers(paths: (string | File)[]): Promise<JdbcDriverInfo[]> {
|
||||
if (paths.some((path) => typeof path !== "string")) {
|
||||
throw new Error("Desktop JDBC driver import requires local file paths");
|
||||
@@ -789,10 +794,18 @@ export async function importJdbcDrivers(paths: (string | File)[]): Promise<JdbcD
|
||||
return invoke("import_jdbc_drivers", { paths });
|
||||
}
|
||||
|
||||
export async function installJdbcDriverFromMaven(coordinate: string, repositories: string[] = []): Promise<JdbcDriverInfo[]> {
|
||||
return invoke("install_jdbc_driver_from_maven", { request: { coordinate, repositories } });
|
||||
}
|
||||
|
||||
export async function deleteJdbcDriver(path: string): Promise<JdbcDriverInfo[]> {
|
||||
return invoke("delete_jdbc_driver", { path });
|
||||
}
|
||||
|
||||
export async function deleteJdbcMavenBundle(bundleId: string): Promise<JdbcDriverInfo[]> {
|
||||
return invoke("delete_jdbc_maven_bundle", { bundleId });
|
||||
}
|
||||
|
||||
export async function jdbcPluginStatus(): Promise<JdbcPluginStatus> {
|
||||
return invoke("jdbc_plugin_status");
|
||||
}
|
||||
@@ -1095,8 +1108,8 @@ export async function redisFlushDb(connectionId: string, db: number): Promise<vo
|
||||
return invoke("redis_flush_db", { connectionId, db });
|
||||
}
|
||||
|
||||
export async function redisExecuteCommand(connectionId: string, db: number, command: string): Promise<RedisCommandResult> {
|
||||
return invoke("redis_execute_command", { connectionId, db, command });
|
||||
export async function redisExecuteCommand(connectionId: string, db: number, command: string, skipSafetyCheck?: boolean): Promise<RedisCommandResult> {
|
||||
return invoke("redis_execute_command", { connectionId, db, command, skipSafetyCheck: skipSafetyCheck ?? false });
|
||||
}
|
||||
|
||||
export async function redisLoadMore(connectionId: string, db: number, keyRaw: string, keyType: string, cursor: number, count: number): Promise<RedisValue> {
|
||||
@@ -1183,6 +1196,10 @@ export async function mongoFindDocuments(connectionId: string, database: string,
|
||||
return invoke("mongo_find_documents", { connectionId, database, collection, skip, limit, filter, sort });
|
||||
}
|
||||
|
||||
export async function documentFindDocuments(connectionId: string, database: string, collection: string, skip: number, limit: number, filter?: string, sort?: string): Promise<MongoDocumentResult> {
|
||||
return invoke("document_find_documents", { connectionId, database, collection, skip, limit, filter, sort });
|
||||
}
|
||||
|
||||
export async function mongoAggregateDocuments(connectionId: string, database: string, collection: string, pipelineJson: string, maxRows?: number): Promise<MongoDocumentResult> {
|
||||
return invoke("mongo_aggregate_documents", { connectionId, database, collection, pipelineJson, maxRows });
|
||||
}
|
||||
|
||||
@@ -476,7 +476,7 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
const node = findNode(treeNodes.value, id);
|
||||
if (node) node.pinned = next.has(id);
|
||||
|
||||
const isConnectionOrGroup = treeNodes.value.some((n) => n.id === id) || treeNodes.value.some((n) => n.type === "connection-group" && n.children?.some((c) => c.id === id));
|
||||
const isConnectionOrGroup = !!findNode(treeNodes.value, id);
|
||||
if (isConnectionOrGroup) {
|
||||
rebuildTreeNodes();
|
||||
} else {
|
||||
@@ -2512,8 +2512,8 @@ export const useConnectionStore = defineStore("connection", () => {
|
||||
fieldLineageSource,
|
||||
databaseSearchSource,
|
||||
databaseExportSource,
|
||||
createConnectionGroup(name: string) {
|
||||
const result = createGroupOp(sidebarLayout.value, name);
|
||||
createConnectionGroup(name: string, parentGroupId?: string | null) {
|
||||
const result = createGroupOp(sidebarLayout.value, name, parentGroupId);
|
||||
updateLayoutAndRebuild(result.layout);
|
||||
return result.groupId;
|
||||
},
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
parseMongoWriteCommand,
|
||||
type MongoAggregateSafetyOptions,
|
||||
} from "@/lib/mongoShellCommand";
|
||||
import { redisCommandResultToQueryResult } from "@/lib/redisQueryResult";
|
||||
import { supportsDatabaseFeature } from "@/lib/databaseCapabilities";
|
||||
import { editablePrimaryKeys } from "@/lib/tableEditing";
|
||||
import { TABLE_DATA_EXPORT_PAGE_SIZE } from "@/lib/tableDataExport";
|
||||
@@ -112,6 +113,8 @@ export const useQueryStore = defineStore("query", () => {
|
||||
const restored = loadSavedTabs();
|
||||
const tabs = ref<QueryTab[]>(restored.tabs);
|
||||
const activeTabId = ref<string | null>(restored.activeTabId);
|
||||
const showCloseConfirm = ref(false);
|
||||
const pendingCloseTabId = ref<string | null>(null);
|
||||
for (const tab of restored.tabs) {
|
||||
if (tab.mode === "data") void deleteTabResultSnapshot(tabResultCacheKey(tab.id));
|
||||
}
|
||||
@@ -262,6 +265,7 @@ export const useQueryStore = defineStore("query", () => {
|
||||
isExplaining: false,
|
||||
mode,
|
||||
};
|
||||
if (mode === "query") tab.originalSql = "";
|
||||
tabs.value.push(tab);
|
||||
activeTabId.value = id;
|
||||
return id;
|
||||
@@ -352,7 +356,26 @@ export const useQueryStore = defineStore("query", () => {
|
||||
return id;
|
||||
}
|
||||
|
||||
function closeTab(id: string) {
|
||||
function isTabDirty(tab: QueryTab): boolean {
|
||||
if (tab.mode !== "query") return false;
|
||||
if (!tab.sql.trim()) return false;
|
||||
const original = tab.originalSql;
|
||||
if (original === undefined) return !!tab.savedSqlId;
|
||||
return tab.sql !== original;
|
||||
}
|
||||
|
||||
function markTabClean(tab: QueryTab | undefined) {
|
||||
if (tab) tab.originalSql = tab.sql;
|
||||
}
|
||||
|
||||
function closeTab(id: string, { force = false }: { force?: boolean } = {}) {
|
||||
const tab = tabs.value.find((t) => t.id === id);
|
||||
if (!tab) return;
|
||||
if (!force && isTabDirty(tab)) {
|
||||
pendingCloseTabId.value = id;
|
||||
showCloseConfirm.value = true;
|
||||
return;
|
||||
}
|
||||
const idx = tabs.value.findIndex((t) => t.id === id);
|
||||
if (idx < 0) return;
|
||||
clearDataGridPendingSnapshotsForTab(id);
|
||||
@@ -367,6 +390,26 @@ export const useQueryStore = defineStore("query", () => {
|
||||
}
|
||||
}
|
||||
|
||||
function forceClosePendingTab() {
|
||||
const id = pendingCloseTabId.value;
|
||||
pendingCloseTabId.value = null;
|
||||
showCloseConfirm.value = false;
|
||||
if (id) closeTab(id, { force: true });
|
||||
}
|
||||
|
||||
function cancelClosePendingTab() {
|
||||
pendingCloseTabId.value = null;
|
||||
showCloseConfirm.value = false;
|
||||
}
|
||||
|
||||
function saveAndClosePendingTab() {
|
||||
const id = pendingCloseTabId.value;
|
||||
pendingCloseTabId.value = null;
|
||||
showCloseConfirm.value = false;
|
||||
if (id) return id;
|
||||
return null;
|
||||
}
|
||||
|
||||
function closeOtherTabs(id: string) {
|
||||
tabs.value
|
||||
.filter((tab) => tab.id !== id)
|
||||
@@ -567,6 +610,7 @@ export const useQueryStore = defineStore("query", () => {
|
||||
schema: file.schema,
|
||||
sql: file.sql,
|
||||
savedSqlId: file.id,
|
||||
originalSql: file.sql,
|
||||
isExecuting: false,
|
||||
isCancelling: false,
|
||||
isExplaining: false,
|
||||
@@ -693,9 +737,9 @@ export const useQueryStore = defineStore("query", () => {
|
||||
await executeCurrentSql(tab.sql);
|
||||
}
|
||||
|
||||
async function executeCurrentSql(sql: string) {
|
||||
async function executeCurrentSql(sql: string, options?: { skipRedisSafetyCheck?: boolean }) {
|
||||
if (!activeTabId.value) return;
|
||||
await executeTabSql(activeTabId.value, sql, { resultBaseSql: sql, resultSortedSql: undefined });
|
||||
await executeTabSql(activeTabId.value, sql, { resultBaseSql: sql, resultSortedSql: undefined, ...options });
|
||||
}
|
||||
|
||||
type QueryMetadataPatch = Pick<QueryTab, "queryAnalysis" | "querySourceColumns" | "queryEditabilityReason" | "tableMeta">;
|
||||
@@ -896,6 +940,7 @@ export const useQueryStore = defineStore("query", () => {
|
||||
mongoSafety?: MongoAggregateSafetyOptions;
|
||||
preserveResultDuringExecution?: boolean;
|
||||
preserveTotalRowCountDuringExecution?: boolean;
|
||||
skipRedisSafetyCheck?: boolean;
|
||||
},
|
||||
) {
|
||||
const tab = tabs.value.find((t) => t.id === id);
|
||||
@@ -943,6 +988,30 @@ export const useQueryStore = defineStore("query", () => {
|
||||
const queryTimeoutSecs = queryTimeoutSecsForConnection(conn);
|
||||
const settingsStore = useSettingsStore();
|
||||
await previousResultSessionClose;
|
||||
|
||||
// Redis command execution
|
||||
if (conn?.db_type === "redis") {
|
||||
await connStore.ensureConnected(tab.connectionId);
|
||||
const redisDb = Number(tab.database) || 0;
|
||||
console.info("[DBX][executeTabSql:redis:start]", { traceId, db: redisDb, sql });
|
||||
const result = await api.redisExecuteCommand(tab.connectionId, redisDb, sql, options?.skipRedisSafetyCheck);
|
||||
console.info("[DBX][executeTabSql:redis:done]", { traceId, elapsed: elapsed() });
|
||||
const current = tabs.value.find((t) => t.id === id);
|
||||
if (current?.executionId === executionId) {
|
||||
current.results = undefined;
|
||||
current.activeResultIndex = undefined;
|
||||
current.result = markQueryResultRowsRaw(redisCommandResultToQueryResult(result.value, performance.now() - startedAt, result.command));
|
||||
touchResult(current);
|
||||
current.queryAnalysis = undefined;
|
||||
current.querySourceColumns = undefined;
|
||||
current.queryEditabilityReason = undefined;
|
||||
current.tableMeta = undefined;
|
||||
current.resultBaseSql = options?.resultBaseSql ?? sql;
|
||||
current.resultSortedSql = options?.resultSortedSql;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (tab.mode === "query") {
|
||||
const pagination = options?.pagination ?? { limit: settingsStore.editorSettings.pageSize, offset: 0 };
|
||||
const plan = await api.prepareQueryPaginationExecutionPlan({
|
||||
@@ -1594,8 +1663,15 @@ export const useQueryStore = defineStore("query", () => {
|
||||
return {
|
||||
tabs,
|
||||
activeTabId,
|
||||
showCloseConfirm,
|
||||
pendingCloseTabId,
|
||||
createTab,
|
||||
closeTab,
|
||||
forceClosePendingTab,
|
||||
cancelClosePendingTab,
|
||||
saveAndClosePendingTab,
|
||||
isTabDirty,
|
||||
markTabClean,
|
||||
closeOtherTabs,
|
||||
closeAllTabs,
|
||||
duplicateTab,
|
||||
|
||||
@@ -49,6 +49,19 @@ function maxOrderIndex(values: Array<{ orderIndex?: number }>) {
|
||||
return values.reduce((max, item) => Math.max(max, item.orderIndex ?? -1), -1);
|
||||
}
|
||||
|
||||
function folderDepth(items: SavedSqlFolder[], folderId: string) {
|
||||
const byId = new Map(items.map((folder) => [folder.id, folder]));
|
||||
const seen = new Set<string>();
|
||||
let depth = 0;
|
||||
let current = byId.get(folderId);
|
||||
while (current?.parentFolderId && !seen.has(current.parentFolderId)) {
|
||||
seen.add(current.parentFolderId);
|
||||
depth++;
|
||||
current = byId.get(current.parentFolderId);
|
||||
}
|
||||
return depth;
|
||||
}
|
||||
|
||||
function loadLegacyState(): SavedSqlState {
|
||||
try {
|
||||
const raw = localStorage.getItem(LEGACY_STORAGE_KEY);
|
||||
@@ -101,7 +114,11 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
}
|
||||
|
||||
function listFolders(connectionId: string) {
|
||||
return sortFoldersByOrder(folders.value.filter((folder) => folder.connectionId === connectionId));
|
||||
return listChildFolders(connectionId);
|
||||
}
|
||||
|
||||
function listChildFolders(connectionId: string, parentFolderId?: string) {
|
||||
return sortFoldersByOrder(folders.value.filter((folder) => folder.connectionId === connectionId && (folder.parentFolderId || "") === (parentFolderId || "")));
|
||||
}
|
||||
|
||||
function listFiles(connectionId: string, folderId?: string) {
|
||||
@@ -112,13 +129,14 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
return files.value.find((file) => file.id === id);
|
||||
}
|
||||
|
||||
async function createFolder(connectionId: string, name: string) {
|
||||
async function createFolder(connectionId: string, name: string, parentFolderId?: string) {
|
||||
const timestamp = nowIso();
|
||||
const folder: SavedSqlFolder = {
|
||||
id: uuid(),
|
||||
connectionId,
|
||||
parentFolderId: parentFolderId || undefined,
|
||||
name,
|
||||
orderIndex: maxOrderIndex(folders.value) + 1,
|
||||
orderIndex: maxOrderIndex(folders.value.filter((item) => item.connectionId === connectionId && (item.parentFolderId || "") === (parentFolderId || ""))) + 1,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
};
|
||||
@@ -139,9 +157,10 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
}
|
||||
|
||||
async function deleteFolder(id: string) {
|
||||
const removedIds = descendantFolderIds(id);
|
||||
await api.deleteSavedSqlFolder(id);
|
||||
folders.value = folders.value.filter((folder) => folder.id !== id);
|
||||
files.value = files.value.filter((file) => file.folderId !== id);
|
||||
folders.value = folders.value.filter((folder) => !removedIds.has(folder.id));
|
||||
files.value = files.value.filter((file) => !file.folderId || !removedIds.has(file.folderId));
|
||||
bumpVersion();
|
||||
await syncToLocalDirectory();
|
||||
}
|
||||
@@ -213,7 +232,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
}
|
||||
|
||||
async function persistFolders(nextFolders: SavedSqlFolder[]) {
|
||||
const reindexed = reindexFolders(nextFolders).map((folder) => ({ ...folder, updatedAt: nowIso() }));
|
||||
const reindexed = nextFolders.map((folder) => ({ ...folder, updatedAt: folder.updatedAt || nowIso() }));
|
||||
await Promise.all(reindexed.map((folder) => api.saveSavedSqlFolder(folder)));
|
||||
folders.value = reindexed;
|
||||
bumpVersion();
|
||||
@@ -229,8 +248,20 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
|
||||
function syncEntries() {
|
||||
const folderById = new Map(folders.value.map((folder) => [folder.id, folder]));
|
||||
const folderPath = (folderId?: string): string | undefined => {
|
||||
if (!folderId) return undefined;
|
||||
const parts: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
let current = folderById.get(folderId);
|
||||
while (current && !seen.has(current.id)) {
|
||||
seen.add(current.id);
|
||||
parts.unshift(current.name);
|
||||
current = current.parentFolderId ? folderById.get(current.parentFolderId) : undefined;
|
||||
}
|
||||
return parts.join("/");
|
||||
};
|
||||
return sortFilesByOrder(files.value).map((file) => ({
|
||||
folderName: file.folderId ? folderById.get(file.folderId)?.name : undefined,
|
||||
folderName: folderPath(file.folderId),
|
||||
fileName: file.name,
|
||||
sql: file.sql,
|
||||
}));
|
||||
@@ -256,16 +287,68 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
}
|
||||
|
||||
async function reorderFolders(draggedId: string, targetId: string, position: "before" | "after") {
|
||||
const ordered = sortFoldersByOrder(folders.value);
|
||||
const dragged = ordered.find((folder) => folder.id === draggedId);
|
||||
const target = ordered.find((folder) => folder.id === targetId);
|
||||
const dragged = folders.value.find((folder) => folder.id === draggedId);
|
||||
const target = folders.value.find((folder) => folder.id === targetId);
|
||||
if (!dragged || !target || dragged.id === target.id) return;
|
||||
if (descendantFolderIds(draggedId).has(targetId)) return;
|
||||
|
||||
const timestamp = nowIso();
|
||||
const targetParentFolderId = target.parentFolderId || undefined;
|
||||
const previousParentFolderId = dragged.parentFolderId || undefined;
|
||||
const ordered = sortFoldersByOrder(folders.value.filter((folder) => (folder.parentFolderId || "") === (targetParentFolderId || "")));
|
||||
const remaining = ordered.filter((folder) => folder.id !== draggedId);
|
||||
const targetIndex = remaining.findIndex((folder) => folder.id === targetId);
|
||||
const insertIndex = position === "before" ? targetIndex : targetIndex + 1;
|
||||
remaining.splice(insertIndex, 0, dragged);
|
||||
await persistFolders(remaining);
|
||||
remaining.splice(insertIndex, 0, { ...dragged, parentFolderId: targetParentFolderId, updatedAt: timestamp });
|
||||
|
||||
const updatedTargetGroup = reindexFolders(remaining).map((folder) => ({
|
||||
...folder,
|
||||
parentFolderId: targetParentFolderId,
|
||||
updatedAt: timestamp,
|
||||
}));
|
||||
const updatedSourceGroup =
|
||||
previousParentFolderId === targetParentFolderId
|
||||
? []
|
||||
: reindexFolders(sortFoldersByOrder(folders.value.filter((folder) => folder.id !== draggedId && (folder.parentFolderId || "") === (previousParentFolderId || "")))).map((folder) => ({
|
||||
...folder,
|
||||
updatedAt: timestamp,
|
||||
}));
|
||||
const untouched = folders.value.filter((folder) => folder.id !== draggedId && (folder.parentFolderId || "") !== (targetParentFolderId || "") && (folder.parentFolderId || "") !== (previousParentFolderId || ""));
|
||||
await persistFolders([...untouched, ...updatedSourceGroup, ...updatedTargetGroup]);
|
||||
}
|
||||
|
||||
function descendantFolderIds(folderId: string) {
|
||||
const ids = new Set<string>([folderId]);
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const folder of folders.value) {
|
||||
if (folder.parentFolderId && ids.has(folder.parentFolderId) && !ids.has(folder.id)) {
|
||||
ids.add(folder.id);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
async function moveFolderToFolder(folderId: string, parentFolderId?: string) {
|
||||
const target = folders.value.find((folder) => folder.id === folderId);
|
||||
if (!target) return;
|
||||
const nextParentFolderId = parentFolderId || undefined;
|
||||
if ((target.parentFolderId || undefined) === nextParentFolderId) return;
|
||||
if (nextParentFolderId && descendantFolderIds(folderId).has(nextParentFolderId)) return;
|
||||
|
||||
const timestamp = nowIso();
|
||||
const previousParentFolderId = target.parentFolderId || undefined;
|
||||
const sourceGroup = reindexFolders(sortFoldersByOrder(folders.value.filter((folder) => folder.id !== folderId && (folder.parentFolderId || "") === (previousParentFolderId || "")))).map((folder) => ({ ...folder, updatedAt: timestamp }));
|
||||
const destinationGroup = reindexFolders([...sortFoldersByOrder(folders.value.filter((folder) => folder.id !== folderId && (folder.parentFolderId || "") === (nextParentFolderId || ""))), { ...target, parentFolderId: nextParentFolderId, updatedAt: timestamp }]).map((folder) => ({
|
||||
...folder,
|
||||
parentFolderId: nextParentFolderId,
|
||||
updatedAt: timestamp,
|
||||
}));
|
||||
const untouched = folders.value.filter((folder) => folder.id !== folderId && (folder.parentFolderId || "") !== (previousParentFolderId || "") && (folder.parentFolderId || "") !== (nextParentFolderId || ""));
|
||||
await persistFolders([...untouched, ...sourceGroup, ...destinationGroup]);
|
||||
}
|
||||
|
||||
async function moveFileToFolder(fileId: string, folderId?: string) {
|
||||
@@ -330,6 +413,16 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
|
||||
const allFolders = computed(() => sortFoldersByOrder(folders.value));
|
||||
|
||||
const allFoldersTreeOrder = computed(() =>
|
||||
[...folders.value].sort((a, b) => {
|
||||
const depthDiff = folderDepth(folders.value, a.id) - folderDepth(folders.value, b.id);
|
||||
if (depthDiff !== 0) return depthDiff;
|
||||
const orderDiff = (a.orderIndex ?? 0) - (b.orderIndex ?? 0);
|
||||
if (orderDiff !== 0) return orderDiff;
|
||||
return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" });
|
||||
}),
|
||||
);
|
||||
|
||||
const allFiles = computed(() => sortFilesByOrder(files.value));
|
||||
|
||||
function filesInFolder(folderId: string) {
|
||||
@@ -351,6 +444,7 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
version,
|
||||
initFromStorage,
|
||||
listFolders,
|
||||
listChildFolders,
|
||||
listFiles,
|
||||
getFile,
|
||||
createFolder,
|
||||
@@ -361,10 +455,12 @@ export const useSavedSqlStore = defineStore("savedSql", () => {
|
||||
recordFileUsage,
|
||||
deleteFile,
|
||||
reorderFolders,
|
||||
moveFolderToFolder,
|
||||
reorderFiles,
|
||||
moveFileToFolder,
|
||||
syncToLocalDirectory,
|
||||
allFolders,
|
||||
allFoldersTreeOrder,
|
||||
allFiles,
|
||||
filesInFolder,
|
||||
filesWithoutFolder,
|
||||
|
||||
@@ -159,6 +159,29 @@ export interface JdbcDriverInfo {
|
||||
name: string;
|
||||
path: string;
|
||||
size: number;
|
||||
bundle_id?: string | null;
|
||||
}
|
||||
|
||||
export interface JdbcMavenArtifactInfo {
|
||||
group_id: string;
|
||||
artifact_id: string;
|
||||
version: string;
|
||||
classifier: string;
|
||||
extension: string;
|
||||
file_name: string;
|
||||
path: string;
|
||||
size: number;
|
||||
sha256: string;
|
||||
}
|
||||
|
||||
export interface JdbcMavenBundleInfo {
|
||||
id: string;
|
||||
coordinate: string;
|
||||
scope: string;
|
||||
repositories: string[];
|
||||
installed_at: string;
|
||||
path: string;
|
||||
artifacts: JdbcMavenArtifactInfo[];
|
||||
}
|
||||
|
||||
export interface JdbcPluginStatus {
|
||||
@@ -334,7 +357,7 @@ export interface ConnectionGroup {
|
||||
collapsed: boolean;
|
||||
}
|
||||
|
||||
export type SidebarOrderEntry = { type: "group"; id: string; connectionIds: string[] } | { type: "connection"; id: string };
|
||||
export type SidebarOrderEntry = { type: "group"; id: string; children?: SidebarOrderEntry[]; connectionIds?: string[] } | { type: "connection"; id: string };
|
||||
|
||||
export interface SidebarLayout {
|
||||
groups: ConnectionGroup[];
|
||||
@@ -372,6 +395,7 @@ export interface QueryTab {
|
||||
schema?: string;
|
||||
sql: string;
|
||||
savedSqlId?: string;
|
||||
originalSql?: string;
|
||||
lastExecutedSql?: string;
|
||||
resultBaseSql?: string;
|
||||
resultSortedSql?: string;
|
||||
@@ -452,6 +476,7 @@ export interface QueryTab {
|
||||
export interface SavedSqlFolder {
|
||||
id: string;
|
||||
connectionId: string;
|
||||
parentFolderId?: string;
|
||||
name: string;
|
||||
orderIndex?: number;
|
||||
createdAt: string;
|
||||
|
||||
@@ -10,7 +10,7 @@ duckdb-bundled = ["duckdb/bundled"]
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
serde_json = { version = "1.0", features = ["preserve_order"] }
|
||||
regex = "1"
|
||||
rayon = "1"
|
||||
percent-encoding = "2"
|
||||
@@ -39,6 +39,7 @@ futures = "0.3"
|
||||
iana-time-zone = "0.1"
|
||||
mongodb = "3.2.5"
|
||||
russh = "0.60"
|
||||
pageant = "0.2"
|
||||
portpicker = "0.1.1"
|
||||
csv = "1"
|
||||
calamine = "0.30.1"
|
||||
|
||||
@@ -46,6 +46,8 @@ pub fn agent_connect_params(config: &ConnectionConfig, host: &str, port: u16, da
|
||||
"client_cert_path": config.client_cert_path,
|
||||
"client_key_path": config.client_key_path,
|
||||
"etcd_endpoints": etcd_endpoints,
|
||||
"jdbc_driver_class": config.jdbc_driver_class.as_deref().unwrap_or(""),
|
||||
"jdbc_driver_paths": &config.jdbc_driver_paths,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -304,9 +304,33 @@ struct SearchHits {
|
||||
hits: Vec<SearchHit>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct HitsTotal {
|
||||
value: u64,
|
||||
enum HitsTotal {
|
||||
Count(u64),
|
||||
Value { value: u64 },
|
||||
}
|
||||
|
||||
impl HitsTotal {
|
||||
fn value(&self) -> u64 {
|
||||
match self {
|
||||
Self::Count(value) | Self::Value { value } => *value,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for HitsTotal {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = serde_json::Value::deserialize(deserializer)?;
|
||||
if let Some(count) = value.as_u64() {
|
||||
return Ok(Self::Count(count));
|
||||
}
|
||||
if let Some(count) = value.get("value").and_then(serde_json::Value::as_u64) {
|
||||
return Ok(Self::Value { value: count });
|
||||
}
|
||||
Err(serde::de::Error::custom("expected hits.total as a number or an object with value"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -322,12 +346,10 @@ pub async fn find_documents(
|
||||
index: &str,
|
||||
skip: u64,
|
||||
limit: i64,
|
||||
filter: Option<&str>,
|
||||
sort: Option<&str>,
|
||||
) -> Result<MongoDocumentResult, String> {
|
||||
let body = serde_json::json!({
|
||||
"from": skip,
|
||||
"size": limit,
|
||||
"sort": ["_doc"],
|
||||
});
|
||||
let body = build_find_documents_body(skip, limit, filter, sort)?;
|
||||
|
||||
let path = format!("/{}/_search", index);
|
||||
let resp = client.post(&path).json(&body).send().await.map_err(|e| format!("Elasticsearch request failed: {e}"))?;
|
||||
@@ -353,11 +375,228 @@ pub async fn find_documents(
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(MongoDocumentResult { documents, total: result.hits.total.value })
|
||||
Ok(MongoDocumentResult { documents, total: result.hits.total.value() })
|
||||
}
|
||||
|
||||
fn build_find_documents_body(
|
||||
skip: u64,
|
||||
limit: i64,
|
||||
filter: Option<&str>,
|
||||
sort: Option<&str>,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let mut body = serde_json::Map::new();
|
||||
body.insert("from".to_string(), serde_json::json!(skip));
|
||||
body.insert("size".to_string(), serde_json::json!(limit));
|
||||
|
||||
if let Some(query) = elasticsearch_query_from_document_filter(filter)? {
|
||||
body.insert("query".to_string(), query);
|
||||
}
|
||||
|
||||
body.insert("sort".to_string(), elasticsearch_sort_from_document_sort(sort)?);
|
||||
Ok(serde_json::Value::Object(body))
|
||||
}
|
||||
|
||||
fn elasticsearch_query_from_document_filter(filter: Option<&str>) -> Result<Option<serde_json::Value>, String> {
|
||||
let Some(filter) = filter.map(str::trim).filter(|value| !value.is_empty()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let value: serde_json::Value = serde_json::from_str(filter).map_err(|e| format!("Invalid filter JSON: {e}"))?;
|
||||
let query = translate_document_filter_value(&value)?;
|
||||
Ok(match query {
|
||||
Some(query) => Some(query),
|
||||
None => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn translate_document_filter_value(value: &serde_json::Value) -> Result<Option<serde_json::Value>, String> {
|
||||
let Some(object) = value.as_object() else {
|
||||
return Err("Elasticsearch filter must be a JSON object".to_string());
|
||||
};
|
||||
if object.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut must = Vec::new();
|
||||
for (key, value) in object {
|
||||
match key.as_str() {
|
||||
"$and" => must.extend(translate_logical_filter_array("$and", value)?),
|
||||
"$or" => {
|
||||
let should = translate_logical_filter_array("$or", value)?;
|
||||
if !should.is_empty() {
|
||||
must.push(serde_json::json!({ "bool": { "should": should, "minimum_should_match": 1 } }));
|
||||
}
|
||||
}
|
||||
key if key.starts_with('$') => {
|
||||
return Err(format!("Unsupported Elasticsearch filter operator: {key}"));
|
||||
}
|
||||
field => must.push(translate_field_filter(field, value)?),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(single_or_bool_filter(must))
|
||||
}
|
||||
|
||||
fn translate_logical_filter_array(operator: &str, value: &serde_json::Value) -> Result<Vec<serde_json::Value>, String> {
|
||||
let items = value.as_array().ok_or_else(|| format!("{operator} must be an array"))?;
|
||||
let mut queries = Vec::new();
|
||||
for item in items {
|
||||
if let Some(query) = translate_document_filter_value(item)? {
|
||||
queries.push(query);
|
||||
}
|
||||
}
|
||||
Ok(queries)
|
||||
}
|
||||
|
||||
fn translate_field_filter(field: &str, value: &serde_json::Value) -> Result<serde_json::Value, String> {
|
||||
let Some(object) = value.as_object() else {
|
||||
return Ok(term_or_null_query(field, value));
|
||||
};
|
||||
if object.keys().any(|key| key.starts_with('$')) {
|
||||
return translate_field_operator_filter(field, object);
|
||||
}
|
||||
Ok(term_or_null_query(field, value))
|
||||
}
|
||||
|
||||
fn translate_field_operator_filter(
|
||||
field: &str,
|
||||
object: &serde_json::Map<String, serde_json::Value>,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let mut must = Vec::new();
|
||||
let mut must_not = Vec::new();
|
||||
let mut range = serde_json::Map::new();
|
||||
|
||||
for (operator, value) in object {
|
||||
match operator.as_str() {
|
||||
"$options" => {}
|
||||
"$ne" => {
|
||||
if value.is_null() {
|
||||
must.push(serde_json::json!({ "exists": { "field": field } }));
|
||||
} else {
|
||||
must_not.push(serde_json::json!({ "term": { field: value.clone() } }));
|
||||
}
|
||||
}
|
||||
"$gt" => {
|
||||
range.insert("gt".to_string(), value.clone());
|
||||
}
|
||||
"$gte" => {
|
||||
range.insert("gte".to_string(), value.clone());
|
||||
}
|
||||
"$lt" => {
|
||||
range.insert("lt".to_string(), value.clone());
|
||||
}
|
||||
"$lte" => {
|
||||
range.insert("lte".to_string(), value.clone());
|
||||
}
|
||||
"$regex" => {
|
||||
must.push(regex_like_query(field, value, object.get("$options"))?);
|
||||
}
|
||||
"$not" => {
|
||||
let Some(inner) = value.as_object() else {
|
||||
return Err("$not must be a JSON object".to_string());
|
||||
};
|
||||
if let Some(regex) = inner.get("$regex") {
|
||||
must_not.push(regex_like_query(
|
||||
field,
|
||||
regex,
|
||||
inner.get("$options").or_else(|| object.get("$options")),
|
||||
)?);
|
||||
} else {
|
||||
return Err("Unsupported Elasticsearch $not filter".to_string());
|
||||
}
|
||||
}
|
||||
other => return Err(format!("Unsupported Elasticsearch field filter operator: {other}")),
|
||||
}
|
||||
}
|
||||
|
||||
if !range.is_empty() {
|
||||
must.push(serde_json::json!({ "range": { field: serde_json::Value::Object(range) } }));
|
||||
}
|
||||
|
||||
match (must.len(), must_not.is_empty()) {
|
||||
(1, true) => Ok(must.remove(0)),
|
||||
(0, false) => Ok(serde_json::json!({ "bool": { "must_not": must_not } })),
|
||||
_ => {
|
||||
let mut bool_query = serde_json::Map::new();
|
||||
if !must.is_empty() {
|
||||
bool_query.insert("must".to_string(), serde_json::Value::Array(must));
|
||||
}
|
||||
if !must_not.is_empty() {
|
||||
bool_query.insert("must_not".to_string(), serde_json::Value::Array(must_not));
|
||||
}
|
||||
Ok(serde_json::json!({ "bool": bool_query }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn term_or_null_query(field: &str, value: &serde_json::Value) -> serde_json::Value {
|
||||
if value.is_null() {
|
||||
serde_json::json!({ "bool": { "must_not": [{ "exists": { "field": field } }] } })
|
||||
} else {
|
||||
serde_json::json!({ "term": { field: value.clone() } })
|
||||
}
|
||||
}
|
||||
|
||||
fn regex_like_query(
|
||||
field: &str,
|
||||
value: &serde_json::Value,
|
||||
options: Option<&serde_json::Value>,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let pattern = value.as_str().ok_or_else(|| "$regex must be a string for Elasticsearch filters".to_string())?;
|
||||
let case_insensitive = options
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.is_some_and(|value| value.chars().any(|ch| ch.eq_ignore_ascii_case(&'i')));
|
||||
Ok(serde_json::json!({
|
||||
"wildcard": {
|
||||
field: {
|
||||
"value": wildcard_contains_pattern(pattern),
|
||||
"case_insensitive": case_insensitive
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
fn wildcard_contains_pattern(pattern: &str) -> String {
|
||||
if pattern.starts_with('*') || pattern.ends_with('*') {
|
||||
pattern.to_string()
|
||||
} else {
|
||||
format!("*{}*", pattern)
|
||||
}
|
||||
}
|
||||
|
||||
fn single_or_bool_filter(mut queries: Vec<serde_json::Value>) -> Option<serde_json::Value> {
|
||||
match queries.len() {
|
||||
0 => None,
|
||||
1 => queries.pop(),
|
||||
_ => Some(serde_json::json!({ "bool": { "filter": queries } })),
|
||||
}
|
||||
}
|
||||
|
||||
fn elasticsearch_sort_from_document_sort(sort: Option<&str>) -> Result<serde_json::Value, String> {
|
||||
let Some(sort) = sort.map(str::trim).filter(|value| !value.is_empty()) else {
|
||||
return Ok(serde_json::json!(["_doc"]));
|
||||
};
|
||||
let value: serde_json::Value = serde_json::from_str(sort).map_err(|e| format!("Invalid sort JSON: {e}"))?;
|
||||
let object = value.as_object().ok_or_else(|| "Elasticsearch sort must be a JSON object".to_string())?;
|
||||
if object.is_empty() {
|
||||
return Ok(serde_json::json!(["_doc"]));
|
||||
}
|
||||
|
||||
let items = object
|
||||
.iter()
|
||||
.map(|(field, direction)| {
|
||||
let order = match direction {
|
||||
serde_json::Value::Number(number) if number.as_i64().unwrap_or(1) < 0 => "desc",
|
||||
serde_json::Value::String(value) if value.eq_ignore_ascii_case("desc") => "desc",
|
||||
_ => "asc",
|
||||
};
|
||||
serde_json::json!({ field: { "order": order } })
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(serde_json::Value::Array(items))
|
||||
}
|
||||
|
||||
pub async fn insert_document(client: &EsClient, index: &str, doc_json: &str) -> Result<String, String> {
|
||||
let doc: serde_json::Value = serde_json::from_str(doc_json).map_err(|e| format!("Invalid JSON: {e}"))?;
|
||||
let doc = elasticsearch_document_body_from_json(doc_json)?;
|
||||
|
||||
let path = format!("/{}/_doc?refresh=true", index);
|
||||
let resp = client.post(&path).json(&doc).send().await.map_err(|e| format!("Elasticsearch request failed: {e}"))?;
|
||||
@@ -372,7 +611,7 @@ pub async fn insert_document(client: &EsClient, index: &str, doc_json: &str) ->
|
||||
}
|
||||
|
||||
pub async fn update_document(client: &EsClient, index: &str, id: &str, doc_json: &str) -> Result<u64, String> {
|
||||
let doc: serde_json::Value = serde_json::from_str(doc_json).map_err(|e| format!("Invalid JSON: {e}"))?;
|
||||
let doc = elasticsearch_document_body_from_json(doc_json)?;
|
||||
|
||||
let path = format!("/{}/_doc/{}?refresh=true", index, id);
|
||||
let resp = client.put(&path).json(&doc).send().await.map_err(|e| format!("Elasticsearch request failed: {e}"))?;
|
||||
@@ -385,6 +624,14 @@ pub async fn update_document(client: &EsClient, index: &str, id: &str, doc_json:
|
||||
Ok(1)
|
||||
}
|
||||
|
||||
fn elasticsearch_document_body_from_json(doc_json: &str) -> Result<serde_json::Value, String> {
|
||||
let mut doc: serde_json::Value = serde_json::from_str(doc_json).map_err(|e| format!("Invalid JSON: {e}"))?;
|
||||
if let serde_json::Value::Object(map) = &mut doc {
|
||||
map.remove("_id");
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
pub async fn delete_document(client: &EsClient, index: &str, id: &str) -> Result<u64, String> {
|
||||
let path = format!("/{}/_doc/{}?refresh=true", index, id);
|
||||
let resp = client.delete(&path).send().await.map_err(|e| format!("Elasticsearch request failed: {e}"))?;
|
||||
@@ -1139,8 +1386,10 @@ fn parse_aggregations(aggs: &serde_json::Map<String, serde_json::Value>) -> (Vec
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
elasticsearch_accept_invalid_certs, elasticsearch_base_url_fallbacks, redact_elasticsearch_url, EsClient,
|
||||
build_find_documents_body, elasticsearch_accept_invalid_certs, elasticsearch_base_url_fallbacks,
|
||||
redact_elasticsearch_url, EsClient, SearchResponse,
|
||||
};
|
||||
use serde_json::json;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
@@ -1189,4 +1438,128 @@ mod tests {
|
||||
"https://user:password@localhost:9200"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_elasticsearch_find_body_with_filter_and_sort() {
|
||||
let body = build_find_documents_body(20, 10, Some(r#"{"city":"长治"}"#), Some(r#"{"created_at":-1}"#)).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
body,
|
||||
json!({
|
||||
"from": 20,
|
||||
"size": 10,
|
||||
"query": { "term": { "city": "长治" } },
|
||||
"sort": [{ "created_at": { "order": "desc" } }]
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_elasticsearch_find_body_with_structured_filter_operators() {
|
||||
let body = build_find_documents_body(
|
||||
0,
|
||||
100,
|
||||
Some(
|
||||
r#"{
|
||||
"$and": [
|
||||
{"city": {"$ne": "上海"}},
|
||||
{"age": {"$gt": 18, "$lte": 60}},
|
||||
{"name": {"$not": {"$regex": "test", "$options": "i"}}}
|
||||
]
|
||||
}"#,
|
||||
),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
body,
|
||||
json!({
|
||||
"from": 0,
|
||||
"size": 100,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{ "bool": { "must_not": [{ "term": { "city": "上海" } }] } },
|
||||
{ "range": { "age": { "gt": 18, "lte": 60 } } },
|
||||
{
|
||||
"bool": {
|
||||
"must_not": [
|
||||
{
|
||||
"wildcard": {
|
||||
"name": {
|
||||
"value": "*test*",
|
||||
"case_insensitive": true
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"sort": ["_doc"]
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_elasticsearch_find_body_with_or_filter() {
|
||||
let body =
|
||||
build_find_documents_body(0, 50, Some(r#"{"$or":[{"city":"长治"},{"city":"上海"}]}"#), None).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
body["query"],
|
||||
json!({
|
||||
"bool": {
|
||||
"should": [
|
||||
{ "term": { "city": "长治" } },
|
||||
{ "term": { "city": "上海" } }
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_search_total_from_elasticsearch_6_number_shape() {
|
||||
let response: SearchResponse = serde_json::from_value(json!({
|
||||
"hits": {
|
||||
"total": 5,
|
||||
"hits": []
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.hits.total.value(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_search_total_from_elasticsearch_7_object_shape() {
|
||||
let response: SearchResponse = serde_json::from_value(json!({
|
||||
"hits": {
|
||||
"total": { "value": 5, "relation": "eq" },
|
||||
"hits": []
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.hits.total.value(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_body_removes_elasticsearch_id_metadata() {
|
||||
let doc = super::elasticsearch_document_body_from_json(r#"{"_id":"abc","name":"Alice"}"#).unwrap();
|
||||
|
||||
assert_eq!(doc, json!({ "name": "Alice" }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_body_preserves_user_field_order() {
|
||||
let doc = super::elasticsearch_document_body_from_json(r#"{"z":1,"_id":"abc","a":2}"#).unwrap();
|
||||
|
||||
assert_eq!(serde_json::to_string(&doc).unwrap(), r#"{"z":1,"a":2}"#);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use mongodb::{
|
||||
bson::{doc, oid::ObjectId, Bson, Document},
|
||||
bson::{doc, oid::ObjectId, Bson, DateTime, Document},
|
||||
options::ClientOptions,
|
||||
Client,
|
||||
};
|
||||
@@ -181,7 +181,8 @@ pub async fn insert_document(
|
||||
collection: &str,
|
||||
doc_json: &str,
|
||||
) -> Result<String, String> {
|
||||
let doc: Document = serde_json::from_str(doc_json).map_err(|e| format!("Invalid JSON: {e}"))?;
|
||||
let value: serde_json::Value = serde_json::from_str(doc_json).map_err(|e| format!("Invalid JSON: {e}"))?;
|
||||
let doc = json_object_to_document(&value).map_err(|e| format!("Invalid document: {e}"))?;
|
||||
let col = client.database(database).collection::<Document>(collection);
|
||||
let result = col.insert_one(doc).await.map_err(|e| e.to_string())?;
|
||||
Ok(format!("{}", result.inserted_id))
|
||||
@@ -216,10 +217,13 @@ pub async fn update_document(
|
||||
id: &str,
|
||||
doc_json: &str,
|
||||
) -> Result<u64, String> {
|
||||
let mut new_doc: Document = serde_json::from_str(doc_json).map_err(|e| format!("Invalid JSON: {e}"))?;
|
||||
new_doc.remove("_id");
|
||||
let value: serde_json::Value = serde_json::from_str(doc_json).map_err(|e| format!("Invalid JSON: {e}"))?;
|
||||
let col = client.database(database).collection::<Document>(collection);
|
||||
for filter in document_id_filters(id) {
|
||||
let current = col.find_one(filter.clone()).await.map_err(|e| e.to_string())?;
|
||||
let mut new_doc = json_object_to_document_preserving_existing(&value, current.as_ref())
|
||||
.map_err(|e| format!("Invalid document: {e}"))?;
|
||||
new_doc.remove("_id");
|
||||
let result = col.replace_one(filter, new_doc.clone()).await.map_err(|e| e.to_string())?;
|
||||
if result.matched_count > 0 {
|
||||
return Ok(result.modified_count);
|
||||
@@ -298,7 +302,10 @@ fn bson_to_json(bson: &Bson) -> serde_json::Value {
|
||||
Bson::Int32(v) => serde_json::json!(v),
|
||||
Bson::Int64(v) => serde_json::json!(v),
|
||||
Bson::ObjectId(oid) => serde_json::Value::String(oid.to_hex()),
|
||||
Bson::DateTime(dt) => serde_json::Value::String(dt.to_string()),
|
||||
Bson::DateTime(dt) => serde_json::Value::String(format!(
|
||||
"ISODate(\"{}\")",
|
||||
dt.try_to_rfc3339_string().unwrap_or_else(|_| dt.to_string())
|
||||
)),
|
||||
Bson::Array(arr) => serde_json::Value::Array(arr.iter().map(bson_to_json).collect()),
|
||||
Bson::Document(doc) => {
|
||||
let mut map = serde_json::Map::new();
|
||||
@@ -320,6 +327,25 @@ pub fn json_object_to_document(value: &serde_json::Value) -> Result<Document, St
|
||||
}
|
||||
}
|
||||
|
||||
fn json_object_to_document_preserving_existing(
|
||||
value: &serde_json::Value,
|
||||
existing: Option<&Document>,
|
||||
) -> Result<Document, String> {
|
||||
match (value, existing) {
|
||||
(serde_json::Value::Object(obj), Some(existing)) => Ok(obj
|
||||
.iter()
|
||||
.map(|(key, value)| {
|
||||
let bson = existing
|
||||
.get(key)
|
||||
.map(|existing_bson| json_value_to_bson_preserving_existing(value, existing_bson))
|
||||
.unwrap_or_else(|| json_value_to_bson(value));
|
||||
(key.clone(), bson)
|
||||
})
|
||||
.collect()),
|
||||
_ => json_object_to_document(value),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn json_filter_to_document(value: &serde_json::Value) -> Result<Document, String> {
|
||||
match json_filter_value_to_bson(value, None) {
|
||||
Bson::Document(doc) => Ok(doc),
|
||||
@@ -327,6 +353,39 @@ pub fn json_filter_to_document(value: &serde_json::Value) -> Result<Document, St
|
||||
}
|
||||
}
|
||||
|
||||
fn json_value_to_bson_preserving_existing(value: &serde_json::Value, existing: &Bson) -> Bson {
|
||||
if &bson_to_json(existing) == value {
|
||||
return existing.clone();
|
||||
}
|
||||
|
||||
match (value, existing) {
|
||||
(serde_json::Value::Array(values), Bson::Array(existing_values)) => Bson::Array(
|
||||
values
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, item)| {
|
||||
existing_values
|
||||
.get(index)
|
||||
.map(|existing_item| json_value_to_bson_preserving_existing(item, existing_item))
|
||||
.unwrap_or_else(|| json_value_to_bson(item))
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
(serde_json::Value::Object(obj), Bson::Document(existing_doc)) => Bson::Document(
|
||||
obj.iter()
|
||||
.map(|(key, item)| {
|
||||
let bson = existing_doc
|
||||
.get(key)
|
||||
.map(|existing_item| json_value_to_bson_preserving_existing(item, existing_item))
|
||||
.unwrap_or_else(|| json_value_to_bson(item));
|
||||
(key.clone(), bson)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
_ => json_value_to_bson(value),
|
||||
}
|
||||
}
|
||||
|
||||
fn json_value_to_bson(value: &serde_json::Value) -> Bson {
|
||||
match value {
|
||||
serde_json::Value::Null => Bson::Null,
|
||||
@@ -350,6 +409,9 @@ fn json_value_to_bson(value: &serde_json::Value) -> Bson {
|
||||
return Bson::ObjectId(oid);
|
||||
}
|
||||
}
|
||||
if let Some(date) = parse_extended_json_date(obj) {
|
||||
return Bson::DateTime(date);
|
||||
}
|
||||
}
|
||||
let doc: Document = obj.iter().map(|(k, v)| (k.clone(), json_value_to_bson(v))).collect();
|
||||
Bson::Document(doc)
|
||||
@@ -357,6 +419,19 @@ fn json_value_to_bson(value: &serde_json::Value) -> Bson {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_extended_json_date(obj: &serde_json::Map<String, serde_json::Value>) -> Option<DateTime> {
|
||||
match obj.get("$date")? {
|
||||
serde_json::Value::String(value) => DateTime::parse_rfc3339_str(value).ok(),
|
||||
serde_json::Value::Number(value) => value.as_i64().map(DateTime::from_millis),
|
||||
serde_json::Value::Object(inner) if inner.len() == 1 => match inner.get("$numberLong") {
|
||||
Some(serde_json::Value::String(value)) => value.parse::<i64>().ok().map(DateTime::from_millis),
|
||||
Some(serde_json::Value::Number(value)) => value.as_i64().map(DateTime::from_millis),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn json_filter_value_to_bson(value: &serde_json::Value, field_name: Option<&str>) -> Bson {
|
||||
if field_name == Some("_id") {
|
||||
if let Some(id) = value.as_str() {
|
||||
@@ -510,4 +585,57 @@ mod tests {
|
||||
|
||||
assert!(matches!(doc.get("owner_id"), Some(Bson::String(value)) if value == id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bson_to_json_displays_date_as_mongo_isodate() {
|
||||
let date = DateTime::parse_rfc3339_str("2026-06-10T13:59:31.287Z").unwrap();
|
||||
let value = bson_to_json(&Bson::DateTime(date));
|
||||
|
||||
assert_eq!(value, serde_json::json!("ISODate(\"2026-06-10T13:59:31.287Z\")"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_object_to_document_parses_extended_json_date() {
|
||||
let value = serde_json::json!({
|
||||
"created_at": { "$date": "2026-06-10T13:59:31.287Z" },
|
||||
"updated_at": { "$date": { "$numberLong": "1781099971287" } }
|
||||
});
|
||||
let doc = json_object_to_document(&value).unwrap();
|
||||
|
||||
assert!(matches!(doc.get("created_at"), Some(Bson::DateTime(_))));
|
||||
assert!(matches!(
|
||||
doc.get("updated_at"),
|
||||
Some(Bson::DateTime(value)) if value.timestamp_millis() == 1_781_099_971_287
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_object_to_document_preserves_unchanged_bson_date_fields() {
|
||||
let date = DateTime::parse_rfc3339_str("2026-06-10T13:59:31.287Z").unwrap();
|
||||
let existing = doc! {
|
||||
"_id": "doc-1",
|
||||
"created_at": Bson::DateTime(date),
|
||||
"name": "before",
|
||||
"profile": {
|
||||
"last_seen": Bson::DateTime(date),
|
||||
"status": "old",
|
||||
},
|
||||
};
|
||||
let displayed = bson_to_json(&Bson::Document(existing.clone()));
|
||||
let mut edited = displayed.as_object().cloned().unwrap();
|
||||
edited.insert("name".to_string(), serde_json::json!("after"));
|
||||
if let Some(serde_json::Value::Object(profile)) = edited.get_mut("profile") {
|
||||
profile.insert("status".to_string(), serde_json::json!("new"));
|
||||
}
|
||||
|
||||
let doc =
|
||||
json_object_to_document_preserving_existing(&serde_json::Value::Object(edited), Some(&existing)).unwrap();
|
||||
|
||||
assert!(matches!(doc.get("created_at"), Some(Bson::DateTime(value)) if *value == date));
|
||||
let Some(Bson::Document(profile)) = doc.get("profile") else {
|
||||
panic!("expected profile document");
|
||||
};
|
||||
assert!(matches!(profile.get("last_seen"), Some(Bson::DateTime(value)) if *value == date));
|
||||
assert!(matches!(profile.get("status"), Some(Bson::String(value)) if value == "new"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1325,7 +1325,7 @@ fn fix_potential_double_encoding(s: &str) -> String {
|
||||
|
||||
pub async fn get_columns(pool: &MySqlPool, database: &str, table: &str) -> Result<Vec<ColumnInfo>, String> {
|
||||
let sql = columns_sql(database, table);
|
||||
let mut conn = pool.get_conn().await.map_err(|e| e.to_string())?;
|
||||
let mut conn = get_conn_with_health_check(pool).await?;
|
||||
let result = match conn.query_iter(&sql).await {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
@@ -1375,7 +1375,7 @@ pub async fn get_columns(pool: &MySqlPool, database: &str, table: &str) -> Resul
|
||||
|
||||
pub async fn get_columns_show(pool: &MySqlPool, database: &str, table: &str) -> Result<Vec<ColumnInfo>, String> {
|
||||
let sql = show_columns_sql(database, table, true);
|
||||
let mut conn = pool.get_conn().await.map_err(|e| e.to_string())?;
|
||||
let mut conn = get_conn_with_health_check(pool).await?;
|
||||
let rows: Vec<mysql_async::Row> = match conn.query_iter(&sql).await {
|
||||
Ok(result) => result.collect_and_drop().await.map_err(|e| e.to_string())?,
|
||||
Err(_) => {
|
||||
|
||||
@@ -1225,15 +1225,112 @@ fn list_objects_sql(include_timestamps: bool) -> &'static str {
|
||||
ORDER BY sort_order, object_name"
|
||||
}
|
||||
|
||||
fn list_objects_legacy_routines_sql(include_timestamps: bool) -> &'static str {
|
||||
if include_timestamps {
|
||||
return "SELECT c.relname AS object_name, \
|
||||
CASE c.relkind \
|
||||
WHEN 'v' THEN 'VIEW' \
|
||||
WHEN 'm' THEN 'VIEW' \
|
||||
WHEN 'S' THEN 'SEQUENCE' \
|
||||
ELSE 'TABLE' \
|
||||
END AS object_type, \
|
||||
obj_description(c.oid) AS object_comment, \
|
||||
stat.creation::text AS created_at, \
|
||||
COALESCE( \
|
||||
CASE WHEN current_setting('track_commit_timestamp', true) = 'on' \
|
||||
THEN pg_xact_commit_timestamp(c.xmin)::text END, \
|
||||
stat.modification::text \
|
||||
) AS updated_at, \
|
||||
CASE WHEN pc.relkind = 'p' THEN pn.nspname ELSE NULL END AS parent_schema, \
|
||||
CASE WHEN pc.relkind = 'p' THEN pc.relname ELSE NULL END AS parent_name, \
|
||||
CASE c.relkind WHEN 'v' THEN 1 WHEN 'm' THEN 1 WHEN 'S' THEN 4 ELSE 0 END AS sort_order \
|
||||
FROM pg_catalog.pg_class c \
|
||||
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
|
||||
LEFT JOIN pg_catalog.pg_inherits i ON i.inhrelid = c.oid \
|
||||
LEFT JOIN pg_catalog.pg_class pc ON pc.oid = i.inhparent \
|
||||
LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = pc.relnamespace \
|
||||
LEFT JOIN LATERAL pg_stat_file( \
|
||||
CASE WHEN c.relkind IN ('r','m','f','p') THEN pg_relation_filepath(c.oid) END, true \
|
||||
) stat ON true \
|
||||
WHERE n.nspname = $1 AND c.relkind IN ('r','v','m','f','p','S') \
|
||||
UNION ALL \
|
||||
SELECT p.proname AS object_name, \
|
||||
CASE WHEN EXISTS ( \
|
||||
SELECT 1 FROM information_schema.routines r \
|
||||
WHERE r.specific_schema = n.nspname \
|
||||
AND r.routine_name = p.proname \
|
||||
AND upper(r.routine_type) = 'PROCEDURE' \
|
||||
) THEN 'PROCEDURE' ELSE 'FUNCTION' END AS object_type, \
|
||||
obj_description(p.oid) AS object_comment, \
|
||||
NULL::text AS created_at, \
|
||||
CASE WHEN current_setting('track_commit_timestamp', true) = 'on' \
|
||||
THEN pg_xact_commit_timestamp(p.xmin)::text END AS updated_at, \
|
||||
NULL::text AS parent_schema, \
|
||||
NULL::text AS parent_name, \
|
||||
CASE WHEN EXISTS ( \
|
||||
SELECT 1 FROM information_schema.routines r \
|
||||
WHERE r.specific_schema = n.nspname \
|
||||
AND r.routine_name = p.proname \
|
||||
AND upper(r.routine_type) = 'PROCEDURE' \
|
||||
) THEN 2 ELSE 3 END AS sort_order \
|
||||
FROM pg_catalog.pg_proc p \
|
||||
JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
|
||||
WHERE n.nspname = $1 AND NOT p.proisagg AND NOT p.proiswindow \
|
||||
ORDER BY sort_order, object_name";
|
||||
}
|
||||
|
||||
"SELECT c.relname AS object_name, \
|
||||
CASE c.relkind \
|
||||
WHEN 'v' THEN 'VIEW' \
|
||||
WHEN 'm' THEN 'VIEW' \
|
||||
WHEN 'S' THEN 'SEQUENCE' \
|
||||
ELSE 'TABLE' \
|
||||
END AS object_type, \
|
||||
obj_description(c.oid) AS object_comment, \
|
||||
NULL::text AS created_at, \
|
||||
NULL::text AS updated_at, \
|
||||
CASE WHEN pc.relkind = 'p' THEN pn.nspname ELSE NULL END AS parent_schema, \
|
||||
CASE WHEN pc.relkind = 'p' THEN pc.relname ELSE NULL END AS parent_name, \
|
||||
CASE c.relkind WHEN 'v' THEN 1 WHEN 'm' THEN 1 WHEN 'S' THEN 4 ELSE 0 END AS sort_order \
|
||||
FROM pg_catalog.pg_class c \
|
||||
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
|
||||
LEFT JOIN pg_catalog.pg_inherits i ON i.inhrelid = c.oid \
|
||||
LEFT JOIN pg_catalog.pg_class pc ON pc.oid = i.inhparent \
|
||||
LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = pc.relnamespace \
|
||||
WHERE n.nspname = $1 AND c.relkind IN ('r','v','m','f','p','S') \
|
||||
UNION ALL \
|
||||
SELECT p.proname AS object_name, \
|
||||
CASE WHEN EXISTS ( \
|
||||
SELECT 1 FROM information_schema.routines r \
|
||||
WHERE r.specific_schema = n.nspname \
|
||||
AND r.routine_name = p.proname \
|
||||
AND upper(r.routine_type) = 'PROCEDURE' \
|
||||
) THEN 'PROCEDURE' ELSE 'FUNCTION' END AS object_type, \
|
||||
obj_description(p.oid) AS object_comment, \
|
||||
NULL::text AS created_at, \
|
||||
NULL::text AS updated_at, \
|
||||
NULL::text AS parent_schema, \
|
||||
NULL::text AS parent_name, \
|
||||
CASE WHEN EXISTS ( \
|
||||
SELECT 1 FROM information_schema.routines r \
|
||||
WHERE r.specific_schema = n.nspname \
|
||||
AND r.routine_name = p.proname \
|
||||
AND upper(r.routine_type) = 'PROCEDURE' \
|
||||
) THEN 2 ELSE 3 END AS sort_order \
|
||||
FROM pg_catalog.pg_proc p \
|
||||
JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
|
||||
WHERE n.nspname = $1 AND NOT p.proisagg AND NOT p.proiswindow \
|
||||
ORDER BY sort_order, object_name"
|
||||
}
|
||||
|
||||
pub async fn list_objects(pool: &Pool, schema: &str) -> Result<Vec<ObjectInfo>, String> {
|
||||
let client = pool.get().await.map_err(|e| e.to_string())?;
|
||||
let stmt = client.prepare_cached(list_objects_sql(true)).await.map_err(|e| e.to_string())?;
|
||||
let rows = match client.query(&stmt, &[&schema]).await {
|
||||
Ok(rows) => rows,
|
||||
Err(_) => {
|
||||
let stmt = client.prepare_cached(list_objects_sql(false)).await.map_err(|e| e.to_string())?;
|
||||
client.query(&stmt, &[&schema]).await.map_err(|e| e.to_string())?
|
||||
}
|
||||
let rows = match client.prepare_cached(list_objects_sql(true)).await {
|
||||
Ok(stmt) => match client.query(&stmt, &[&schema]).await {
|
||||
Ok(rows) => rows,
|
||||
Err(_) => query_list_objects_fallbacks(&client, schema).await?,
|
||||
},
|
||||
Err(_) => query_list_objects_fallbacks(&client, schema).await?,
|
||||
};
|
||||
|
||||
Ok(rows
|
||||
@@ -1251,6 +1348,22 @@ pub async fn list_objects(pool: &Pool, schema: &str) -> Result<Vec<ObjectInfo>,
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn query_list_objects_fallbacks(
|
||||
client: &deadpool_postgres::Object,
|
||||
schema: &str,
|
||||
) -> Result<Vec<tokio_postgres::Row>, String> {
|
||||
for sql in
|
||||
[list_objects_sql(false), list_objects_legacy_routines_sql(true), list_objects_legacy_routines_sql(false)]
|
||||
{
|
||||
if let Ok(stmt) = client.prepare_cached(sql).await {
|
||||
if let Ok(rows) = client.query(&stmt, &[&schema]).await {
|
||||
return Ok(rows);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err("failed to list PostgreSQL objects with compatible metadata queries".to_string())
|
||||
}
|
||||
|
||||
pub async fn list_schemas(pool: &Pool) -> Result<Vec<String>, String> {
|
||||
let client = pool.get().await.map_err(|e| e.to_string())?;
|
||||
let stmt = client
|
||||
@@ -2153,6 +2266,20 @@ mod tests {
|
||||
assert!(list_objects_sql(false).contains("pg_catalog.pg_proc"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_list_objects_sql_avoids_pg11_prokind() {
|
||||
let sql = list_objects_legacy_routines_sql(false);
|
||||
|
||||
assert!(sql.contains("pg_catalog.pg_proc"));
|
||||
assert!(sql.contains("information_schema.routines"));
|
||||
assert!(sql.contains("'PROCEDURE'"));
|
||||
assert!(sql.contains("'FUNCTION'"));
|
||||
assert!(sql.contains("NOT p.proisagg"));
|
||||
assert!(sql.contains("NOT p.proiswindow"));
|
||||
assert!(!sql.contains("p.prokind"));
|
||||
assert!(sql.contains("'SEQUENCE'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_recovery_statement_detection_matches_common_postgres_commands() {
|
||||
assert!(is_transaction_recovery_statement("ROLLBACK"));
|
||||
|
||||
@@ -635,6 +635,8 @@ fn parse_cluster_slot_master(value: RedisRawValue, fallback_host: &str) -> Resul
|
||||
}
|
||||
|
||||
pub fn parse_command_argv(command_text: &str) -> Result<Vec<String>, String> {
|
||||
// Strip trailing semicolons so commands like "HGETALL aaa;" work naturally
|
||||
let command_text = command_text.trim_end().trim_end_matches(';');
|
||||
let mut argv = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut chars = command_text.chars().peekable();
|
||||
@@ -797,14 +799,18 @@ where
|
||||
redis::cmd("FLUSHDB").query_async::<()>(con).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn execute_command<C>(con: &mut C, command_text: &str) -> Result<RedisCommandResult, String>
|
||||
pub async fn execute_command<C>(
|
||||
con: &mut C,
|
||||
command_text: &str,
|
||||
skip_safety_check: bool,
|
||||
) -> Result<RedisCommandResult, String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
let argv = parse_command_argv(command_text)?;
|
||||
let command = argv[0].to_ascii_uppercase();
|
||||
let safety = classify_command(&command);
|
||||
if safety == RedisCommandSafety::Blocked {
|
||||
if !skip_safety_check && safety == RedisCommandSafety::Blocked {
|
||||
return Err(format!("Redis command is blocked for safety: {command}"));
|
||||
}
|
||||
|
||||
|
||||
@@ -127,13 +127,22 @@ async fn try_authenticate_with_agent(
|
||||
ssh_user: &str,
|
||||
connect_timeout: &Duration,
|
||||
) -> Result<(), String> {
|
||||
let mut agent = match connect_ssh_agent().await {
|
||||
#[cfg(unix)]
|
||||
let mut agent = match AgentClient::connect_env().await {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
return Err(format!("No SSH password or key provided, and ssh-agent is unavailable: {e}"));
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(windows)]
|
||||
let mut agent = {
|
||||
let stream = pageant::PageantStream::new()
|
||||
.await
|
||||
.map_err(|e| format!("No SSH password or key provided, and ssh-agent (Pageant) is unavailable: {e}"))?;
|
||||
AgentClient::connect(stream)
|
||||
};
|
||||
|
||||
let identities = match agent.request_identities().await {
|
||||
Ok(ids) if ids.is_empty() => {
|
||||
return Err("No SSH password or key provided, and ssh-agent has no identities".to_string());
|
||||
|
||||
+371
-12
@@ -1,7 +1,10 @@
|
||||
use crate::agent_service::AgentProgressEvent;
|
||||
use crate::plugins::{PluginManifest, SUPPORTED_PLUGIN_PROTOCOL_VERSION};
|
||||
use crate::update::{fetch_latest_release, is_newer_version, JdbcPluginLatest};
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::{Path, PathBuf};
|
||||
use tokio::process::Command;
|
||||
|
||||
const JDBC_PLUGIN_DOWNLOAD_URL: &str =
|
||||
"https://github.com/t8y2/dbx/releases/latest/download/dbx-jdbc-plugin-latest.zip";
|
||||
@@ -12,6 +15,38 @@ pub struct JdbcDriverInfo {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub size: u64,
|
||||
pub bundle_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct JdbcMavenInstallRequest {
|
||||
pub coordinate: String,
|
||||
#[serde(default)]
|
||||
pub repositories: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct JdbcMavenBundleInfo {
|
||||
pub id: String,
|
||||
pub coordinate: String,
|
||||
pub scope: String,
|
||||
pub repositories: Vec<String>,
|
||||
pub installed_at: String,
|
||||
pub path: String,
|
||||
pub artifacts: Vec<JdbcMavenArtifactInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct JdbcMavenArtifactInfo {
|
||||
pub group_id: String,
|
||||
pub artifact_id: String,
|
||||
pub version: String,
|
||||
pub classifier: String,
|
||||
pub extension: String,
|
||||
pub file_name: String,
|
||||
pub path: String,
|
||||
pub size: u64,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -32,6 +67,10 @@ pub fn list_jdbc_drivers(plugins_root: &Path) -> Result<Vec<JdbcDriverInfo>, Str
|
||||
list_jdbc_drivers_from_dir(&jdbc_drivers_dir(plugins_root))
|
||||
}
|
||||
|
||||
pub fn list_jdbc_maven_bundles(plugins_root: &Path) -> Result<Vec<JdbcMavenBundleInfo>, String> {
|
||||
list_jdbc_maven_bundles_from_dir(&jdbc_maven_drivers_dir(plugins_root))
|
||||
}
|
||||
|
||||
pub fn import_jdbc_drivers(plugins_root: &Path, paths: &[String]) -> Result<Vec<JdbcDriverInfo>, String> {
|
||||
let drivers_dir = jdbc_drivers_dir(plugins_root);
|
||||
std::fs::create_dir_all(&drivers_dir).map_err(|err| err.to_string())?;
|
||||
@@ -70,6 +109,63 @@ pub fn delete_jdbc_driver(plugins_root: &Path, path: &str) -> Result<Vec<JdbcDri
|
||||
list_jdbc_drivers_from_dir(&drivers_dir)
|
||||
}
|
||||
|
||||
pub fn delete_jdbc_maven_bundle(plugins_root: &Path, bundle_id: &str) -> Result<Vec<JdbcDriverInfo>, String> {
|
||||
if !is_safe_bundle_id(bundle_id) {
|
||||
return Err("Invalid JDBC Maven bundle id".to_string());
|
||||
}
|
||||
let bundles_dir = jdbc_maven_drivers_dir(plugins_root);
|
||||
let target = bundles_dir.join(bundle_id);
|
||||
if target.exists() {
|
||||
std::fs::remove_dir_all(&target).map_err(|err| err.to_string())?;
|
||||
}
|
||||
list_jdbc_drivers(plugins_root)
|
||||
}
|
||||
|
||||
pub async fn install_jdbc_driver_from_maven(
|
||||
plugins_root: &Path,
|
||||
request: JdbcMavenInstallRequest,
|
||||
) -> Result<Vec<JdbcDriverInfo>, String> {
|
||||
let coordinate = request.coordinate.trim().to_string();
|
||||
if coordinate.is_empty() {
|
||||
return Err("Maven coordinate is required".to_string());
|
||||
}
|
||||
let plugin_dir = plugins_root.join("jdbc");
|
||||
let resolver = jdbc_maven_resolver_executable(&plugin_dir);
|
||||
if !resolver.exists() {
|
||||
return Err("JDBC Maven resolver is not installed. Update or reinstall the JDBC plugin.".to_string());
|
||||
}
|
||||
|
||||
let mut repositories = if request.repositories.is_empty() {
|
||||
vec!["https://repo.maven.apache.org/maven2/".to_string()]
|
||||
} else {
|
||||
request.repositories.into_iter().map(|repo| repo.trim().to_string()).filter(|repo| !repo.is_empty()).collect()
|
||||
};
|
||||
if repositories.is_empty() {
|
||||
repositories.push("https://repo.maven.apache.org/maven2/".to_string());
|
||||
}
|
||||
let local_repo = plugin_dir.join("maven-cache");
|
||||
std::fs::create_dir_all(&local_repo).map_err(|err| err.to_string())?;
|
||||
|
||||
let mut command = Command::new(&resolver);
|
||||
command.arg("resolve").arg("--coordinate").arg(&coordinate).arg("--local-repo").arg(&local_repo);
|
||||
for repo in &repositories {
|
||||
command.arg("--repo").arg(repo);
|
||||
}
|
||||
let output = command.output().await.map_err(|err| format!("Failed to run JDBC Maven resolver: {err}"))?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return Err(if stderr.is_empty() { "JDBC Maven resolver failed".to_string() } else { stderr });
|
||||
}
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let resolved: MavenResolveOutput =
|
||||
serde_json::from_str(&stdout).map_err(|err| format!("Failed to parse JDBC Maven resolver output: {err}"))?;
|
||||
let root = plugins_root.to_path_buf();
|
||||
tokio::task::spawn_blocking(move || install_jdbc_maven_bundle(&root, &coordinate, &resolved))
|
||||
.await
|
||||
.map_err(|err| err.to_string())??;
|
||||
list_jdbc_drivers(plugins_root)
|
||||
}
|
||||
|
||||
// ---- JDBC Plugin ----
|
||||
|
||||
pub async fn get_jdbc_plugin_status(plugins_root: &Path) -> Result<JdbcPluginStatus, String> {
|
||||
@@ -77,13 +173,23 @@ pub async fn get_jdbc_plugin_status(plugins_root: &Path) -> Result<JdbcPluginSta
|
||||
}
|
||||
|
||||
pub async fn install_jdbc_plugin(plugins_root: &Path) -> Result<JdbcPluginStatus, String> {
|
||||
let bytes = download_jdbc_plugin_zip().await?;
|
||||
install_jdbc_plugin_with_progress(plugins_root, |_| {}).await
|
||||
}
|
||||
|
||||
pub async fn install_jdbc_plugin_with_progress(
|
||||
plugins_root: &Path,
|
||||
progress: impl Fn(AgentProgressEvent),
|
||||
) -> Result<JdbcPluginStatus, String> {
|
||||
let bytes = download_jdbc_plugin_zip_with_progress(&progress).await?;
|
||||
let plugin_dir = plugins_root.join("jdbc");
|
||||
let status_dir = plugin_dir.clone();
|
||||
progress(AgentProgressEvent::transfer("jdbc-plugin-extract", 0, 0));
|
||||
tokio::task::spawn_blocking(move || install_jdbc_plugin_zip(&bytes, &plugin_dir))
|
||||
.await
|
||||
.map_err(|err| err.to_string())??;
|
||||
jdbc_plugin_status_from_dir(&status_dir).await
|
||||
let status = jdbc_plugin_status_from_dir(&status_dir).await;
|
||||
progress(AgentProgressEvent::step("done"));
|
||||
status
|
||||
}
|
||||
|
||||
pub async fn install_jdbc_plugin_from_file(plugins_root: &Path, file_path: &str) -> Result<JdbcPluginStatus, String> {
|
||||
@@ -147,6 +253,21 @@ fn jdbc_drivers_dir(plugins_root: &Path) -> PathBuf {
|
||||
plugins_root.join("jdbc").join("drivers")
|
||||
}
|
||||
|
||||
fn jdbc_maven_drivers_dir(plugins_root: &Path) -> PathBuf {
|
||||
jdbc_drivers_dir(plugins_root).join("maven")
|
||||
}
|
||||
|
||||
fn jdbc_maven_resolver_executable(plugin_dir: &Path) -> PathBuf {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
plugin_dir.join("bin").join("dbx-maven-resolver.bat")
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
plugin_dir.join("bin").join("dbx-maven-resolver")
|
||||
}
|
||||
}
|
||||
|
||||
async fn jdbc_plugin_status_from_dir(plugin_dir: &Path) -> Result<JdbcPluginStatus, String> {
|
||||
let manifest_path = plugin_dir.join("manifest.json");
|
||||
let manifest = match std::fs::read_to_string(&manifest_path) {
|
||||
@@ -192,19 +313,30 @@ async fn latest_jdbc_plugin() -> Option<JdbcPluginLatest> {
|
||||
fetch_latest_release().await.ok().and_then(|release| release.jdbc_plugin)
|
||||
}
|
||||
|
||||
async fn download_jdbc_plugin_zip() -> Result<Vec<u8>, String> {
|
||||
async fn download_jdbc_plugin_zip_with_progress(progress: &impl Fn(AgentProgressEvent)) -> Result<Vec<u8>, String> {
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(60))
|
||||
.build()
|
||||
.map_err(|err| err.to_string())?;
|
||||
|
||||
let resp =
|
||||
let mut resp =
|
||||
crate::race_download(&client, JDBC_PLUGIN_DOWNLOAD_URL, JDBC_PLUGIN_R2_PATH, "dbx-jdbc-plugin-installer")
|
||||
.await
|
||||
.map_err(|err| format!("Failed to download JDBC plugin: {err}"))?;
|
||||
|
||||
let bytes = resp.bytes().await.map_err(|err| err.to_string())?;
|
||||
Ok(bytes.to_vec())
|
||||
let total = resp.content_length().unwrap_or(0);
|
||||
progress(AgentProgressEvent::transfer("jdbc-plugin", 0, total));
|
||||
let mut downloaded = 0;
|
||||
let mut bytes = Vec::with_capacity(total.try_into().unwrap_or(0));
|
||||
while let Some(chunk) = resp.chunk().await.map_err(|err| err.to_string())? {
|
||||
downloaded += chunk.len() as u64;
|
||||
bytes.extend_from_slice(&chunk);
|
||||
progress(AgentProgressEvent::transfer("jdbc-plugin", downloaded, total));
|
||||
}
|
||||
if total == 0 {
|
||||
progress(AgentProgressEvent::transfer("jdbc-plugin", downloaded, downloaded));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn install_jdbc_plugin_zip(bytes: &[u8], plugin_dir: &Path) -> Result<(), String> {
|
||||
@@ -270,11 +402,13 @@ fn install_jdbc_plugin_zip(bytes: &[u8], plugin_dir: &Path) -> Result<(), String
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let executable = plugin_dir.join("bin").join("dbx-jdbc-plugin");
|
||||
if executable.exists() {
|
||||
let mut permissions = std::fs::metadata(&executable).map_err(|err| err.to_string())?.permissions();
|
||||
permissions.set_mode(0o755);
|
||||
std::fs::set_permissions(executable, permissions).map_err(|err| err.to_string())?;
|
||||
for executable in ["dbx-jdbc-plugin", "dbx-maven-resolver"] {
|
||||
let executable = plugin_dir.join("bin").join(executable);
|
||||
if executable.exists() {
|
||||
let mut permissions = std::fs::metadata(&executable).map_err(|err| err.to_string())?.permissions();
|
||||
permissions.set_mode(0o755);
|
||||
std::fs::set_permissions(executable, permissions).map_err(|err| err.to_string())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -317,6 +451,10 @@ fn list_jdbc_drivers_from_dir(drivers_dir: &Path) -> Result<Vec<JdbcDriverInfo>,
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|err| err.to_string())?;
|
||||
let path = entry.path();
|
||||
if path.file_name().and_then(|name| name.to_str()) == Some("maven") && path.is_dir() {
|
||||
append_jdbc_maven_driver_jars(&mut drivers, &path)?;
|
||||
continue;
|
||||
}
|
||||
if path.extension().and_then(|ext| ext.to_str()).map(|ext| ext.eq_ignore_ascii_case("jar")) != Some(true) {
|
||||
continue;
|
||||
}
|
||||
@@ -325,12 +463,183 @@ fn list_jdbc_drivers_from_dir(drivers_dir: &Path) -> Result<Vec<JdbcDriverInfo>,
|
||||
name: path.file_name().and_then(|name| name.to_str()).unwrap_or("driver.jar").to_string(),
|
||||
path: path.to_string_lossy().to_string(),
|
||||
size: metadata.len(),
|
||||
bundle_id: None,
|
||||
});
|
||||
}
|
||||
drivers.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
Ok(drivers)
|
||||
}
|
||||
|
||||
fn append_jdbc_maven_driver_jars(drivers: &mut Vec<JdbcDriverInfo>, maven_dir: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(maven_dir) {
|
||||
Ok(entries) => entries,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(err) => return Err(err.to_string()),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|err| err.to_string())?;
|
||||
let bundle_dir = entry.path();
|
||||
if !bundle_dir.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let bundle_id = entry.file_name().to_string_lossy().to_string();
|
||||
let jars_dir = bundle_dir.join("jars");
|
||||
let jars = match std::fs::read_dir(&jars_dir) {
|
||||
Ok(jars) => jars,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err.to_string()),
|
||||
};
|
||||
for jar in jars {
|
||||
let jar = jar.map_err(|err| err.to_string())?;
|
||||
let path = jar.path();
|
||||
if path.extension().and_then(|ext| ext.to_str()).map(|ext| ext.eq_ignore_ascii_case("jar")) != Some(true) {
|
||||
continue;
|
||||
}
|
||||
let metadata = jar.metadata().map_err(|err| err.to_string())?;
|
||||
drivers.push(JdbcDriverInfo {
|
||||
name: path.file_name().and_then(|name| name.to_str()).unwrap_or("driver.jar").to_string(),
|
||||
path: path.to_string_lossy().to_string(),
|
||||
size: metadata.len(),
|
||||
bundle_id: Some(bundle_id.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn list_jdbc_maven_bundles_from_dir(maven_dir: &Path) -> Result<Vec<JdbcMavenBundleInfo>, String> {
|
||||
let entries = match std::fs::read_dir(maven_dir) {
|
||||
Ok(entries) => entries,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]),
|
||||
Err(err) => return Err(err.to_string()),
|
||||
};
|
||||
let mut bundles = Vec::new();
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|err| err.to_string())?;
|
||||
let manifest_path = entry.path().join("manifest.json");
|
||||
if !manifest_path.exists() {
|
||||
continue;
|
||||
}
|
||||
let raw = std::fs::read_to_string(&manifest_path).map_err(|err| err.to_string())?;
|
||||
bundles.push(serde_json::from_str::<JdbcMavenBundleInfo>(&raw).map_err(|err| err.to_string())?);
|
||||
}
|
||||
bundles.sort_by(|a, b| a.coordinate.cmp(&b.coordinate));
|
||||
Ok(bundles)
|
||||
}
|
||||
|
||||
fn install_jdbc_maven_bundle(
|
||||
plugins_root: &Path,
|
||||
coordinate: &str,
|
||||
resolved: &MavenResolveOutput,
|
||||
) -> Result<(), String> {
|
||||
if resolved.artifacts.is_empty() {
|
||||
return Err("Maven resolver did not return any JAR artifacts".to_string());
|
||||
}
|
||||
let bundle_id = maven_bundle_id(coordinate);
|
||||
let bundle_dir = jdbc_maven_drivers_dir(plugins_root).join(&bundle_id);
|
||||
let temp_dir = bundle_dir.with_extension("tmp");
|
||||
if temp_dir.exists() {
|
||||
std::fs::remove_dir_all(&temp_dir).map_err(|err| err.to_string())?;
|
||||
}
|
||||
std::fs::create_dir_all(temp_dir.join("jars")).map_err(|err| err.to_string())?;
|
||||
|
||||
let mut artifacts = Vec::new();
|
||||
for artifact in &resolved.artifacts {
|
||||
if !artifact.extension.eq_ignore_ascii_case("jar") {
|
||||
continue;
|
||||
}
|
||||
let source = PathBuf::from(&artifact.file);
|
||||
if !source.exists() {
|
||||
return Err(format!("Resolved artifact file does not exist: {}", source.display()));
|
||||
}
|
||||
let file_name = source
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.ok_or_else(|| format!("Invalid resolved artifact path: {}", source.display()))?;
|
||||
let target = unique_target_path(&temp_dir.join("jars"), file_name);
|
||||
std::fs::copy(&source, &target)
|
||||
.map_err(|err| format!("Failed to copy {} to {}: {err}", source.display(), target.display()))?;
|
||||
let metadata = std::fs::metadata(&target).map_err(|err| err.to_string())?;
|
||||
let sha256 = file_sha256(&target)?;
|
||||
let final_path = bundle_dir.join("jars").join(target.file_name().unwrap_or_default());
|
||||
artifacts.push(JdbcMavenArtifactInfo {
|
||||
group_id: artifact.group_id.clone(),
|
||||
artifact_id: artifact.artifact_id.clone(),
|
||||
version: artifact.version.clone(),
|
||||
classifier: artifact.classifier.clone(),
|
||||
extension: artifact.extension.clone(),
|
||||
file_name: target.file_name().and_then(|name| name.to_str()).unwrap_or(file_name).to_string(),
|
||||
path: final_path.to_string_lossy().to_string(),
|
||||
size: metadata.len(),
|
||||
sha256,
|
||||
});
|
||||
}
|
||||
if artifacts.is_empty() {
|
||||
return Err("Maven resolver did not return any JAR artifacts".to_string());
|
||||
}
|
||||
let manifest = JdbcMavenBundleInfo {
|
||||
id: bundle_id.clone(),
|
||||
coordinate: resolved.coordinate.clone(),
|
||||
scope: resolved.scope.clone(),
|
||||
repositories: resolved.repositories.clone(),
|
||||
installed_at: chrono::Utc::now().to_rfc3339(),
|
||||
path: bundle_dir.to_string_lossy().to_string(),
|
||||
artifacts,
|
||||
};
|
||||
let manifest_json = serde_json::to_string_pretty(&manifest).map_err(|err| err.to_string())?;
|
||||
std::fs::write(temp_dir.join("manifest.json"), manifest_json).map_err(|err| err.to_string())?;
|
||||
if bundle_dir.exists() {
|
||||
std::fs::remove_dir_all(&bundle_dir).map_err(|err| err.to_string())?;
|
||||
}
|
||||
std::fs::rename(&temp_dir, &bundle_dir).map_err(|err| err.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn maven_bundle_id(coordinate: &str) -> String {
|
||||
let mut id = String::with_capacity(coordinate.len());
|
||||
for ch in coordinate.trim().chars() {
|
||||
if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-') {
|
||||
id.push(ch);
|
||||
} else {
|
||||
id.push('_');
|
||||
}
|
||||
}
|
||||
if id.is_empty() {
|
||||
"maven-driver".to_string()
|
||||
} else {
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
fn is_safe_bundle_id(bundle_id: &str) -> bool {
|
||||
!bundle_id.is_empty() && bundle_id.chars().all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '_'))
|
||||
}
|
||||
|
||||
fn file_sha256(path: &Path) -> Result<String, String> {
|
||||
let bytes = std::fs::read(path).map_err(|err| err.to_string())?;
|
||||
let hash = Sha256::digest(bytes);
|
||||
Ok(format!("{hash:x}"))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct MavenResolveOutput {
|
||||
coordinate: String,
|
||||
scope: String,
|
||||
repositories: Vec<String>,
|
||||
artifacts: Vec<MavenResolvedArtifact>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct MavenResolvedArtifact {
|
||||
group_id: String,
|
||||
artifact_id: String,
|
||||
version: String,
|
||||
classifier: String,
|
||||
extension: String,
|
||||
file: String,
|
||||
}
|
||||
|
||||
pub fn unique_target_path(dir: &Path, file_name: &str) -> PathBuf {
|
||||
let target = dir.join(file_name);
|
||||
if !target.exists() {
|
||||
@@ -348,3 +657,53 @@ pub fn unique_target_path(dir: &Path, file_name: &str) -> PathBuf {
|
||||
}
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn maven_bundle_install_lists_nested_jars() {
|
||||
let root = std::env::temp_dir().join(format!("dbx-jdbc-maven-test-{}", uuid::Uuid::new_v4()));
|
||||
let source_dir = root.join("source");
|
||||
std::fs::create_dir_all(&source_dir).unwrap();
|
||||
let source = source_dir.join("demo-driver.jar");
|
||||
std::fs::write(&source, b"jar").unwrap();
|
||||
|
||||
let resolved = MavenResolveOutput {
|
||||
coordinate: "com.example:demo-driver:1.0.0".to_string(),
|
||||
scope: "runtime".to_string(),
|
||||
repositories: vec!["https://repo.maven.apache.org/maven2/".to_string()],
|
||||
artifacts: vec![MavenResolvedArtifact {
|
||||
group_id: "com.example".to_string(),
|
||||
artifact_id: "demo-driver".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
classifier: String::new(),
|
||||
extension: "jar".to_string(),
|
||||
file: source.to_string_lossy().to_string(),
|
||||
}],
|
||||
};
|
||||
|
||||
install_jdbc_maven_bundle(&root, "com.example:demo-driver:1.0.0", &resolved).unwrap();
|
||||
let drivers = list_jdbc_drivers(&root).unwrap();
|
||||
assert_eq!(drivers.len(), 1);
|
||||
assert_eq!(drivers[0].name, "demo-driver.jar");
|
||||
assert_eq!(drivers[0].bundle_id.as_deref(), Some("com.example_demo-driver_1.0.0"));
|
||||
|
||||
let bundles = list_jdbc_maven_bundles(&root).unwrap();
|
||||
assert_eq!(bundles.len(), 1);
|
||||
assert_eq!(bundles[0].artifacts.len(), 1);
|
||||
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_bundle_ids_are_path_safe() {
|
||||
assert_eq!(
|
||||
maven_bundle_id("org.apache.hive:hive-jdbc:4.0.1:standalone"),
|
||||
"org.apache.hive_hive-jdbc_4.0.1_standalone"
|
||||
);
|
||||
assert!(is_safe_bundle_id("org.apache.hive_hive-jdbc_4.0.1_standalone"));
|
||||
assert!(!is_safe_bundle_id("../hive"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ pub async fn mongo_list_collections_core(
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn mongo_find_documents_core(
|
||||
pub async fn document_find_documents_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
@@ -90,7 +90,7 @@ pub async fn mongo_find_documents_core(
|
||||
PoolKind::Elasticsearch(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
elasticsearch_driver::find_documents(&client, collection, skip, limit).await
|
||||
elasticsearch_driver::find_documents(&client, collection, skip, limit, filter, sort).await
|
||||
}
|
||||
PoolKind::Agent(client) => {
|
||||
let mut client = client.lock().await;
|
||||
@@ -109,6 +109,19 @@ pub async fn mongo_find_documents_core(
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mongo_find_documents_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
collection: &str,
|
||||
skip: u64,
|
||||
limit: i64,
|
||||
filter: Option<&str>,
|
||||
sort: Option<&str>,
|
||||
) -> Result<MongoDocumentResult, String> {
|
||||
document_find_documents_core(state, connection_id, database, collection, skip, limit, filter, sort).await
|
||||
}
|
||||
|
||||
pub async fn mongo_aggregate_documents_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
|
||||
@@ -433,6 +433,7 @@ fn spawn_plugin_child(plugin: &InstalledPlugin, env: &PluginRuntimeEnv) -> Resul
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
#[allow(unused_imports)]
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
|
||||
@@ -656,6 +656,7 @@ pub async fn redis_execute_command_core(
|
||||
connection_id: &str,
|
||||
db: u32,
|
||||
command: &str,
|
||||
skip_safety_check: bool,
|
||||
) -> Result<RedisCommandResult, String> {
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
@@ -663,7 +664,7 @@ pub async fn redis_execute_command_core(
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_driver::select_db(&mut *con, db).await?;
|
||||
redis_driver::execute_command(&mut *con, command).await
|
||||
redis_driver::execute_command(&mut *con, command, skip_safety_check).await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
redis_driver::ensure_cluster_db(db)?;
|
||||
@@ -673,7 +674,7 @@ pub async fn redis_execute_command_core(
|
||||
}
|
||||
}
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_driver::execute_command(&mut *con, command).await
|
||||
redis_driver::execute_command(&mut *con, command, skip_safety_check).await
|
||||
}
|
||||
},
|
||||
_ => Err("Not a Redis connection".to_string()),
|
||||
|
||||
@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
|
||||
pub struct SavedSqlFolder {
|
||||
pub id: String,
|
||||
pub connection_id: String,
|
||||
pub parent_folder_id: Option<String>,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub order_index: i64,
|
||||
|
||||
@@ -1060,6 +1060,19 @@ pub fn postgres_object_source_sql(schema: &str, name: &str, kind: &db::ObjectSou
|
||||
}
|
||||
}
|
||||
|
||||
pub fn postgres_routine_object_source_legacy_sql(schema: &str, name: &str) -> String {
|
||||
format!(
|
||||
"SELECT pg_get_functiondef(p.oid) \
|
||||
FROM pg_proc p \
|
||||
JOIN pg_namespace n ON n.oid = p.pronamespace \
|
||||
WHERE n.nspname = {} AND p.proname = {} \
|
||||
AND NOT p.proisagg AND NOT p.proiswindow \
|
||||
ORDER BY p.oid LIMIT 1",
|
||||
sql_string(schema),
|
||||
sql_string(name)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn oracle_object_source_sql(schema: &str, name: &str, kind: &db::ObjectSourceKind) -> String {
|
||||
let object_type = match kind {
|
||||
db::ObjectSourceKind::View => "VIEW",
|
||||
@@ -1313,6 +1326,13 @@ async fn postgres_object_source(
|
||||
.and_then(first_string_cell)
|
||||
.map_err(|fallback_err| format!("{primary_err}; fallback failed: {fallback_err}"))
|
||||
}
|
||||
Err(primary_err) if matches!(object_type, db::ObjectSourceKind::Procedure | db::ObjectSourceKind::Function) => {
|
||||
let fallback_sql = postgres_routine_object_source_legacy_sql(schema, name);
|
||||
db::postgres::execute_query(pool, &fallback_sql)
|
||||
.await
|
||||
.and_then(first_string_cell)
|
||||
.map_err(|fallback_err| format!("{primary_err}; fallback failed: {fallback_err}"))
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
@@ -1342,6 +1362,16 @@ mod object_source_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_postgres_legacy_routine_source_sql_without_prokind() {
|
||||
let sql = postgres_routine_object_source_legacy_sql("public", "recalc_score");
|
||||
|
||||
assert!(sql.contains("pg_get_functiondef(p.oid)"));
|
||||
assert!(sql.contains("NOT p.proisagg"));
|
||||
assert!(sql.contains("NOT p.proiswindow"));
|
||||
assert!(!sql.contains("p.prokind"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_postgres_object_source_sql_for_sequences() {
|
||||
let sql = postgres_object_source_sql("tenant's schema", "order id seq", &ObjectSourceKind::Sequence);
|
||||
|
||||
+244
-2
@@ -56,6 +56,7 @@ pub struct SqlFileImportStatement {
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct SqlParsingOptions {
|
||||
pub supports_hash_line_comments: bool,
|
||||
pub supports_oracle_plsql_blocks: bool,
|
||||
}
|
||||
|
||||
impl SqlParsingOptions {
|
||||
@@ -65,11 +66,15 @@ impl SqlParsingOptions {
|
||||
db_type,
|
||||
DatabaseType::Mysql | DatabaseType::Doris | DatabaseType::StarRocks | DatabaseType::Goldendb
|
||||
),
|
||||
supports_oracle_plsql_blocks: matches!(
|
||||
db_type,
|
||||
DatabaseType::Oracle | DatabaseType::Dameng | DatabaseType::Gaussdb | DatabaseType::OceanbaseOracle
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mysql_compatible() -> Self {
|
||||
Self { supports_hash_line_comments: true }
|
||||
Self { supports_hash_line_comments: true, ..Self::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,6 +257,12 @@ impl SqlStatementSplitter {
|
||||
';' if !self.in_single_quote && !self.in_double_quote && !self.in_backtick => {
|
||||
if self.custom_delimiter.is_some() {
|
||||
self.buffer.push(ch);
|
||||
} else if self.options.supports_oracle_plsql_blocks && starts_with_oracle_plsql_block(&self.buffer)
|
||||
{
|
||||
self.buffer.push(ch);
|
||||
if oracle_plsql_block_is_complete(&self.buffer) {
|
||||
self.push_current_statement(&mut statements);
|
||||
}
|
||||
} else {
|
||||
self.push_current_statement(&mut statements);
|
||||
}
|
||||
@@ -264,6 +275,16 @@ impl SqlStatementSplitter {
|
||||
let buf_end = self.buffer.len() - 1;
|
||||
let last_line_start = self.buffer[..buf_end].rfind('\n').map_or(0, |p| p + 1);
|
||||
let last_line = self.buffer[last_line_start..buf_end].trim();
|
||||
if self.options.supports_oracle_plsql_blocks && last_line == "/" {
|
||||
let before = self.buffer[..last_line_start].trim();
|
||||
if has_executable_sql_with_options(before, self.options) {
|
||||
statements.push(before.to_string());
|
||||
}
|
||||
self.buffer.clear();
|
||||
self.previous = None;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some(new_delim) = parse_delimiter_command(last_line) {
|
||||
self.custom_delimiter = if new_delim == ";" { None } else { Some(new_delim.to_string()) };
|
||||
if last_line_start > 0 {
|
||||
@@ -303,6 +324,12 @@ impl SqlStatementSplitter {
|
||||
statements.push(before.to_string());
|
||||
}
|
||||
self.buffer.clear();
|
||||
} else if self.options.supports_oracle_plsql_blocks && last_line == "/" {
|
||||
let before = trimmed.rsplit_once('\n').map(|x| x.0).unwrap_or("").trim();
|
||||
if has_executable_sql_with_options(before, self.options) {
|
||||
statements.push(before.to_string());
|
||||
}
|
||||
self.buffer.clear();
|
||||
} else if let Some(ref delim) = self.custom_delimiter {
|
||||
if self.buffer.ends_with(delim.as_str()) {
|
||||
self.buffer.truncate(self.buffer.len() - delim.len());
|
||||
@@ -471,6 +498,12 @@ fn split_sql_statement_ranges_with_options(sql: &str, options: SqlParsingOptions
|
||||
if ch == '\n' {
|
||||
let line_start = sql[..i].rfind('\n').map_or(0, |pos| pos + 1);
|
||||
let line = sql[line_start..i].trim();
|
||||
if options.supports_oracle_plsql_blocks && line == "/" {
|
||||
push_statement_range(&mut ranges, sql, start, line_start, options);
|
||||
start = i + ch.len_utf8();
|
||||
i = start;
|
||||
continue;
|
||||
}
|
||||
if let Some(new_delimiter) = parse_delimiter_command(line) {
|
||||
let before = sql[start..line_start].trim();
|
||||
if has_executable_sql_with_options(before, options) {
|
||||
@@ -498,7 +531,17 @@ fn split_sql_statement_ranges_with_options(sql: &str, options: SqlParsingOptions
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
';' if !in_single_quote && !in_double_quote && !in_backtick && custom_delimiter.is_none() => {
|
||||
push_statement_range(&mut ranges, sql, start, i, options);
|
||||
let is_oracle_plsql =
|
||||
options.supports_oracle_plsql_blocks && starts_with_oracle_plsql_block(&sql[start..i]);
|
||||
if is_oracle_plsql {
|
||||
if !oracle_plsql_block_is_complete(&sql[start..i + ch.len_utf8()]) {
|
||||
i += ch.len_utf8();
|
||||
continue;
|
||||
}
|
||||
push_statement_range(&mut ranges, sql, start, i + ch.len_utf8(), options);
|
||||
} else {
|
||||
push_statement_range(&mut ranges, sql, start, i, options);
|
||||
}
|
||||
i += ch.len_utf8();
|
||||
start = i;
|
||||
}
|
||||
@@ -523,6 +566,10 @@ fn split_sql_statement_ranges_with_options(sql: &str, options: SqlParsingOptions
|
||||
if let Some(line_start) = sql[start..].rfind('\n').map(|pos| start + pos + 1) {
|
||||
push_statement_range(&mut ranges, sql, start, line_start, options);
|
||||
}
|
||||
} else if options.supports_oracle_plsql_blocks && last_line == "/" {
|
||||
if let Some(line_start) = sql[start..].rfind('\n').map(|pos| start + pos + 1) {
|
||||
push_statement_range(&mut ranges, sql, start, line_start, options);
|
||||
}
|
||||
} else {
|
||||
push_statement_range(&mut ranges, sql, start, sql.len(), options);
|
||||
}
|
||||
@@ -1362,6 +1409,135 @@ fn first_executable_sql_token_with_options(sql: &str, options: SqlParsingOptions
|
||||
(i > start).then_some(&sql[start..i])
|
||||
}
|
||||
|
||||
fn starts_with_oracle_plsql_block(sql: &str) -> bool {
|
||||
let tokens = oracle_plsql_tokens(sql);
|
||||
match tokens.as_slice() {
|
||||
[first, ..] if first.eq_ignore_ascii_case("DECLARE") => true,
|
||||
[first, second, ..]
|
||||
if first.eq_ignore_ascii_case("BEGIN") && !matches!(second.as_str(), ";" | "TRANSACTION" | "WORK") =>
|
||||
{
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn oracle_plsql_block_is_complete(sql: &str) -> bool {
|
||||
if !starts_with_oracle_plsql_block(sql) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut depth = 0usize;
|
||||
let mut saw_begin = false;
|
||||
let mut complete = false;
|
||||
let mut pending_end: Option<bool> = None;
|
||||
|
||||
for token in oracle_plsql_tokens(sql) {
|
||||
if token == ";" {
|
||||
if let Some(is_block_end) = pending_end.take() {
|
||||
if is_block_end && depth > 0 {
|
||||
depth -= 1;
|
||||
complete = depth == 0;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(is_block_end) = pending_end.as_mut() {
|
||||
if matches!(token.as_str(), "IF" | "LOOP" | "CASE") {
|
||||
*is_block_end = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if token == "BEGIN" {
|
||||
depth += 1;
|
||||
saw_begin = true;
|
||||
complete = false;
|
||||
} else if token == "END" {
|
||||
pending_end = Some(true);
|
||||
}
|
||||
}
|
||||
|
||||
saw_begin && complete
|
||||
}
|
||||
|
||||
fn oracle_plsql_tokens(sql: &str) -> Vec<String> {
|
||||
let mut tokens = Vec::new();
|
||||
let mut iter = sql.char_indices().peekable();
|
||||
|
||||
while let Some((_, ch)) = iter.next() {
|
||||
if ch.is_whitespace() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ch == '-' && iter.peek().is_some_and(|(_, next)| *next == '-') {
|
||||
iter.next();
|
||||
for (_, comment_ch) in iter.by_ref() {
|
||||
if comment_ch == '\n' {
|
||||
break;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ch == '/' && iter.peek().is_some_and(|(_, next)| *next == '*') {
|
||||
iter.next();
|
||||
let mut previous = '\0';
|
||||
for (_, comment_ch) in iter.by_ref() {
|
||||
if previous == '*' && comment_ch == '/' {
|
||||
break;
|
||||
}
|
||||
previous = comment_ch;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ch == '\'' {
|
||||
while let Some((_, quote_ch)) = iter.next() {
|
||||
if quote_ch == '\'' {
|
||||
if iter.peek().is_some_and(|(_, next)| *next == '\'') {
|
||||
iter.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ch == '"' {
|
||||
for (_, ident_ch) in iter.by_ref() {
|
||||
if ident_ch == '"' {
|
||||
break;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ch == ';' {
|
||||
tokens.push(";".to_string());
|
||||
continue;
|
||||
}
|
||||
|
||||
if ch.is_ascii_alphabetic() || ch == '_' {
|
||||
let mut token = String::new();
|
||||
token.push(ch.to_ascii_uppercase());
|
||||
while let Some((_, next)) = iter.peek().copied() {
|
||||
if next.is_ascii_alphanumeric() || next == '_' || next == '$' || next == '#' {
|
||||
token.push(next.to_ascii_uppercase());
|
||||
iter.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
tokens.push(token);
|
||||
}
|
||||
}
|
||||
|
||||
tokens
|
||||
}
|
||||
|
||||
fn starts_with_chars(chars: &[char], start: usize, needle: &[char]) -> bool {
|
||||
start + needle.len() <= chars.len() && chars[start..start + needle.len()] == *needle
|
||||
}
|
||||
@@ -1912,6 +2088,72 @@ DELIMITER ;";
|
||||
assert_eq!(super::split_sql_statements(sql), vec!["SELECT 1", "SELECT 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oracle_like_split_keeps_anonymous_plsql_block_together() {
|
||||
let sql = "\
|
||||
DECLARE
|
||||
V_EXISTS_FLAG NUMBER;
|
||||
BEGIN
|
||||
SELECT COUNT(1)
|
||||
INTO V_EXISTS_FLAG
|
||||
FROM SCHEMA_NAME.TABLE_NAME
|
||||
WHERE UNIQUE_KEY_COLUMN = 'BUSINESS_UNIQUE_VALUE';
|
||||
IF V_EXISTS_FLAG = 0 THEN
|
||||
INSERT INTO SCHEMA_NAME.TABLE_NAME (UNIQUE_KEY_COLUMN, COLUMN_NAME_1)
|
||||
VALUES ('BUSINESS_UNIQUE_VALUE', 'BUSINESS_VALUE_1');
|
||||
END IF;
|
||||
END;";
|
||||
|
||||
assert_eq!(split_sql_statements_for_database(sql, DatabaseType::Oracle), vec![sql.to_string()]);
|
||||
assert_eq!(split_sql_statements_for_database(sql, DatabaseType::Dameng), vec![sql.to_string()]);
|
||||
assert_eq!(split_sql_statements_for_database(sql, DatabaseType::Gaussdb), vec![sql.to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oracle_like_split_treats_slash_line_as_plsql_delimiter() {
|
||||
let sql = "\
|
||||
BEGIN
|
||||
NULL;
|
||||
END;
|
||||
/
|
||||
SELECT 1;";
|
||||
|
||||
assert_eq!(
|
||||
split_sql_statements_for_database(sql, DatabaseType::Oracle),
|
||||
vec!["BEGIN\n NULL;\nEND;", "SELECT 1"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oracle_like_current_statement_keeps_plsql_block_together() {
|
||||
let sql = "\
|
||||
DECLARE
|
||||
v_exists_flag NUMBER;
|
||||
BEGIN
|
||||
IF v_exists_flag = 0 THEN
|
||||
NULL;
|
||||
END IF;
|
||||
END;
|
||||
/
|
||||
SELECT 1;";
|
||||
let cursor = sql[..sql.find("NULL").unwrap()].encode_utf16().count();
|
||||
let next_cursor = sql[..sql.find("SELECT 1").unwrap()].encode_utf16().count();
|
||||
|
||||
assert_eq!(
|
||||
find_statement_at_cursor_for_database(sql, cursor, DatabaseType::Oracle),
|
||||
"DECLARE\n v_exists_flag NUMBER;\nBEGIN\n IF v_exists_flag = 0 THEN\n NULL;\n END IF;\nEND;"
|
||||
);
|
||||
assert_eq!(find_statement_at_cursor_for_database(sql, next_cursor, DatabaseType::Oracle), "SELECT 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oracle_like_split_keeps_transaction_begin_as_statement() {
|
||||
assert_eq!(
|
||||
split_sql_statements_for_database("BEGIN; INSERT INTO t VALUES (1); COMMIT;", DatabaseType::Gaussdb),
|
||||
vec!["BEGIN", "INSERT INTO t VALUES (1)", "COMMIT"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_statement_at_cursor() {
|
||||
let sql = "SELECT 1; SELECT 2";
|
||||
|
||||
@@ -130,6 +130,7 @@ const SCHEMA_STATEMENTS: &[&str] = &[
|
||||
"CREATE TABLE IF NOT EXISTS saved_sql_folders (
|
||||
id TEXT PRIMARY KEY,
|
||||
connection_id TEXT NOT NULL,
|
||||
parent_folder_id TEXT,
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
order_index INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT '',
|
||||
@@ -209,7 +210,8 @@ fn ensure_history_columns_sync(conn: &Connection) -> Result<(), String> {
|
||||
}
|
||||
|
||||
fn ensure_saved_sql_columns_sync(conn: &Connection) -> Result<(), String> {
|
||||
const FOLDER_COLUMNS: &[(&str, &str)] = &[("order_index", "INTEGER NOT NULL DEFAULT 0")];
|
||||
const FOLDER_COLUMNS: &[(&str, &str)] =
|
||||
&[("parent_folder_id", "TEXT"), ("order_index", "INTEGER NOT NULL DEFAULT 0")];
|
||||
const FILE_COLUMNS: &[(&str, &str)] = &[
|
||||
("order_index", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("open_count", "INTEGER NOT NULL DEFAULT 0"),
|
||||
@@ -860,11 +862,12 @@ impl Storage {
|
||||
|
||||
for folder in &library.folders {
|
||||
tx.execute(
|
||||
"INSERT INTO saved_sql_folders (id, connection_id, name, order_index, created_at, updated_at) \
|
||||
VALUES (?, ?, ?, ?, ?, ?)",
|
||||
"INSERT INTO saved_sql_folders (id, connection_id, parent_folder_id, name, order_index, created_at, updated_at) \
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
params![
|
||||
folder.id,
|
||||
folder.connection_id,
|
||||
folder.parent_folder_id,
|
||||
folder.name,
|
||||
folder.order_index,
|
||||
folder.created_at,
|
||||
@@ -906,8 +909,8 @@ impl Storage {
|
||||
self.with_conn(|conn| {
|
||||
let mut folder_stmt = conn
|
||||
.prepare(
|
||||
"SELECT id, connection_id, name, order_index, created_at, updated_at \
|
||||
FROM saved_sql_folders ORDER BY order_index, connection_id, name COLLATE NOCASE",
|
||||
"SELECT id, connection_id, parent_folder_id, name, order_index, created_at, updated_at \
|
||||
FROM saved_sql_folders ORDER BY COALESCE(parent_folder_id, ''), order_index, connection_id, name COLLATE NOCASE",
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let folders = folder_stmt
|
||||
@@ -915,10 +918,11 @@ impl Storage {
|
||||
Ok(SavedSqlFolder {
|
||||
id: row.get(0)?,
|
||||
connection_id: row.get(1)?,
|
||||
name: row.get(2)?,
|
||||
order_index: row.get(3)?,
|
||||
created_at: row.get(4)?,
|
||||
updated_at: row.get(5)?,
|
||||
parent_folder_id: row.get(2)?,
|
||||
name: row.get(3)?,
|
||||
order_index: row.get(4)?,
|
||||
created_at: row.get(5)?,
|
||||
updated_at: row.get(6)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| e.to_string())?
|
||||
@@ -961,16 +965,18 @@ impl Storage {
|
||||
let folder = folder.clone();
|
||||
self.with_conn(move |conn| {
|
||||
conn.execute(
|
||||
"INSERT INTO saved_sql_folders (id, connection_id, name, order_index, created_at, updated_at) \
|
||||
VALUES (?, ?, ?, ?, ?, ?) \
|
||||
"INSERT INTO saved_sql_folders (id, connection_id, parent_folder_id, name, order_index, created_at, updated_at) \
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?) \
|
||||
ON CONFLICT(id) DO UPDATE SET \
|
||||
connection_id = excluded.connection_id, \
|
||||
parent_folder_id = excluded.parent_folder_id, \
|
||||
name = excluded.name, \
|
||||
order_index = excluded.order_index, \
|
||||
updated_at = excluded.updated_at",
|
||||
params![
|
||||
folder.id,
|
||||
folder.connection_id,
|
||||
folder.parent_folder_id,
|
||||
folder.name,
|
||||
folder.order_index,
|
||||
folder.created_at,
|
||||
@@ -987,8 +993,27 @@ impl Storage {
|
||||
let id = id.to_string();
|
||||
self.with_conn(move |conn| {
|
||||
let tx = conn.transaction().map_err(|e| e.to_string())?;
|
||||
tx.execute("DELETE FROM saved_sql_files WHERE folder_id = ?1", [id.as_str()]).map_err(|e| e.to_string())?;
|
||||
tx.execute("DELETE FROM saved_sql_folders WHERE id = ?1", [id.as_str()]).map_err(|e| e.to_string())?;
|
||||
let mut folder_ids = vec![id.clone()];
|
||||
let mut index = 0;
|
||||
while index < folder_ids.len() {
|
||||
let parent_id = folder_ids[index].clone();
|
||||
let mut stmt = tx
|
||||
.prepare("SELECT id FROM saved_sql_folders WHERE parent_folder_id = ?1")
|
||||
.map_err(|e| e.to_string())?;
|
||||
let child_ids = stmt
|
||||
.query_map([parent_id.as_str()], |row| row.get::<_, String>(0))
|
||||
.map_err(|e| e.to_string())?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| e.to_string())?;
|
||||
folder_ids.extend(child_ids);
|
||||
index += 1;
|
||||
}
|
||||
for folder_id in folder_ids.iter().rev() {
|
||||
tx.execute("DELETE FROM saved_sql_files WHERE folder_id = ?1", [folder_id.as_str()])
|
||||
.map_err(|e| e.to_string())?;
|
||||
tx.execute("DELETE FROM saved_sql_folders WHERE id = ?1", [folder_id.as_str()])
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
tx.commit().map_err(|e| e.to_string())
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -6,6 +6,7 @@ use super::util::{
|
||||
clean, format_default_for_sql, normalize_default, original_comment, original_default, qualified_table, quote_ident,
|
||||
quote_string,
|
||||
};
|
||||
use crate::table_structure_sql::ColumnExtra;
|
||||
|
||||
pub fn build_single_column_alter_sql(options: SingleColumnAlterSqlOptions) -> TableStructureSqlResult {
|
||||
let capabilities = capabilities_for(options.database_type);
|
||||
@@ -88,12 +89,20 @@ pub fn build_single_column_alter_sql(options: SingleColumnAlterSqlOptions) -> Ta
|
||||
TableStructureSqlResult { statements, warnings }
|
||||
}
|
||||
|
||||
fn is_column_extra_empty(extra: &ColumnExtra) -> bool {
|
||||
!extra.auto_increment.unwrap_or(false)
|
||||
&& !extra.on_update_current_timestamp.unwrap_or(false)
|
||||
&& extra.identity.is_none()
|
||||
}
|
||||
|
||||
pub(super) fn has_column_extra_change(column: &EditableStructureColumn) -> bool {
|
||||
let Some(original) = &column.original else { return false };
|
||||
let current_extra = column.extra.as_ref();
|
||||
match (current_extra, original.extra.as_deref()) {
|
||||
// Neither has extra → no change
|
||||
(None, None | Some("")) => false,
|
||||
// Current extra is empty (all None) → no effective extra
|
||||
(Some(curr), _) if is_column_extra_empty(curr) => false,
|
||||
// Extra added or removed
|
||||
(Some(_), None | Some("")) => true,
|
||||
(None, Some(_)) => true,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::column_alter::{
|
||||
build_clickhouse_existing_column_sql, build_h2_existing_column_sql, build_mysql_existing_column_sql,
|
||||
build_oracle_like_existing_column_sql, build_postgres_existing_column_sql, build_sqlite_existing_column_sql,
|
||||
build_sqlserver_existing_column_sql, has_existing_column_attribute_change,
|
||||
build_sqlserver_existing_column_sql, has_column_extra_change, has_existing_column_attribute_change,
|
||||
};
|
||||
use super::column_format::column_definition;
|
||||
use super::comments::build_sqlserver_column_comment_sql;
|
||||
@@ -64,7 +64,7 @@ pub(super) fn build_column_sql(options: &TableStructureSqlOptions, warnings: &mu
|
||||
continue;
|
||||
}
|
||||
|
||||
if !has_existing_column_attribute_change(column) && !has_position_change {
|
||||
if !has_existing_column_attribute_change(column) && !has_column_extra_change(column) && !has_position_change {
|
||||
continue;
|
||||
}
|
||||
let original = column.original.as_ref().unwrap();
|
||||
@@ -72,7 +72,8 @@ pub(super) fn build_column_sql(options: &TableStructureSqlOptions, warnings: &mu
|
||||
let has_attribute_change = column.data_type.trim() != original.data_type.trim()
|
||||
|| column.is_nullable != original.is_nullable
|
||||
|| normalize_default(Some(&column.default_value)) != original_default(column)
|
||||
|| clean(&column.comment) != original_comment(column);
|
||||
|| clean(&column.comment) != original_comment(column)
|
||||
|| has_column_extra_change(column);
|
||||
if has_position_change && !capabilities.reorder_column {
|
||||
warnings.push(format!("Reordering columns is not supported for {database_label} from this editor."));
|
||||
}
|
||||
|
||||
@@ -102,6 +102,11 @@ async fn main() {
|
||||
.route("/plugins", get(routes::plugins::list_plugins))
|
||||
// JDBC
|
||||
.route("/jdbc/drivers", get(routes::jdbc::list_jdbc_drivers).post(routes::jdbc::import_jdbc_drivers))
|
||||
.route(
|
||||
"/jdbc/drivers/maven",
|
||||
get(routes::jdbc::list_jdbc_maven_bundles).post(routes::jdbc::install_jdbc_driver_from_maven),
|
||||
)
|
||||
.route("/jdbc/drivers/maven/{bundle_id}", delete(routes::jdbc::delete_jdbc_maven_bundle))
|
||||
.route("/jdbc/drivers/{name}", delete(routes::jdbc::delete_jdbc_driver))
|
||||
.route("/jdbc/plugin/status", get(routes::jdbc::get_jdbc_plugin_status))
|
||||
.route("/jdbc/plugin/install", post(routes::jdbc::install_jdbc_plugin))
|
||||
@@ -257,6 +262,7 @@ async fn main() {
|
||||
// MongoDB
|
||||
.route("/mongo/list-databases", post(routes::mongo::list_databases))
|
||||
.route("/mongo/list-collections", post(routes::mongo::list_collections))
|
||||
.route("/document-store/find-documents", post(routes::mongo::document_find_documents))
|
||||
.route("/mongo/find-documents", post(routes::mongo::find_documents))
|
||||
.route("/mongo/aggregate-documents", post(routes::mongo::aggregate_documents))
|
||||
.route("/mongo/insert-document", post(routes::mongo::insert_document))
|
||||
|
||||
@@ -2,7 +2,9 @@ use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Multipart, Path, State};
|
||||
use axum::Json;
|
||||
use dbx_core::jdbc::{self, JdbcDriverInfo, JdbcPluginStatus};
|
||||
use dbx_core::agent_service::AgentProgressEvent;
|
||||
use dbx_core::jdbc::{self, JdbcDriverInfo, JdbcMavenBundleInfo, JdbcMavenInstallRequest, JdbcPluginStatus};
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::state::WebState;
|
||||
@@ -14,6 +16,21 @@ pub async fn list_jdbc_drivers(State(state): State<Arc<WebState>>) -> Result<Jso
|
||||
Ok(Json(jdbc::list_jdbc_drivers(root).map_err(AppError::internal)?))
|
||||
}
|
||||
|
||||
pub async fn list_jdbc_maven_bundles(
|
||||
State(state): State<Arc<WebState>>,
|
||||
) -> Result<Json<Vec<JdbcMavenBundleInfo>>, AppError> {
|
||||
let root = state.app.plugins.root_dir();
|
||||
Ok(Json(jdbc::list_jdbc_maven_bundles(root).map_err(AppError::internal)?))
|
||||
}
|
||||
|
||||
pub async fn install_jdbc_driver_from_maven(
|
||||
State(state): State<Arc<WebState>>,
|
||||
Json(req): Json<JdbcMavenInstallRequest>,
|
||||
) -> Result<Json<Vec<JdbcDriverInfo>>, AppError> {
|
||||
let root = state.app.plugins.root_dir();
|
||||
Ok(Json(jdbc::install_jdbc_driver_from_maven(root, req).await.map_err(AppError::internal)?))
|
||||
}
|
||||
|
||||
pub async fn import_jdbc_drivers(
|
||||
State(state): State<Arc<WebState>>,
|
||||
mut multipart: Multipart,
|
||||
@@ -50,6 +67,14 @@ pub async fn delete_jdbc_driver(
|
||||
Ok(Json(jdbc::delete_jdbc_driver(root, &path_str).map_err(AppError::internal)?))
|
||||
}
|
||||
|
||||
pub async fn delete_jdbc_maven_bundle(
|
||||
State(state): State<Arc<WebState>>,
|
||||
Path(bundle_id): Path<String>,
|
||||
) -> Result<Json<Vec<JdbcDriverInfo>>, AppError> {
|
||||
let root = state.app.plugins.root_dir();
|
||||
Ok(Json(jdbc::delete_jdbc_maven_bundle(root, &bundle_id).map_err(AppError::internal)?))
|
||||
}
|
||||
|
||||
// ---- JDBC Plugin ----
|
||||
|
||||
pub async fn get_jdbc_plugin_status(State(state): State<Arc<WebState>>) -> Result<Json<JdbcPluginStatus>, AppError> {
|
||||
@@ -59,7 +84,12 @@ pub async fn get_jdbc_plugin_status(State(state): State<Arc<WebState>>) -> Resul
|
||||
|
||||
pub async fn install_jdbc_plugin(State(state): State<Arc<WebState>>) -> Result<Json<JdbcPluginStatus>, AppError> {
|
||||
let root = state.app.plugins.root_dir();
|
||||
Ok(Json(jdbc::install_jdbc_plugin(root).await.map_err(AppError::internal)?))
|
||||
let tx = progress_sender(&state, "global").await;
|
||||
Ok(Json(
|
||||
jdbc::install_jdbc_plugin_with_progress(root, |event| send_progress_event(&tx, event))
|
||||
.await
|
||||
.map_err(AppError::internal)?,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn install_jdbc_plugin_local(
|
||||
@@ -97,3 +127,20 @@ pub async fn uninstall_jdbc_plugin(State(state): State<Arc<WebState>>) -> Result
|
||||
pub async fn list_system_fonts() -> Result<Json<Vec<String>>, AppError> {
|
||||
Ok(Json(jdbc::list_system_fonts()))
|
||||
}
|
||||
|
||||
async fn progress_sender(state: &WebState, operation_id: &str) -> broadcast::Sender<String> {
|
||||
let mut channels = state.sse_channels.write().await;
|
||||
channels
|
||||
.entry(format!("agent-install-progress:{operation_id}"))
|
||||
.or_insert_with(|| {
|
||||
let (tx, _) = broadcast::channel::<String>(256);
|
||||
tx
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn send_progress_event(tx: &broadcast::Sender<String>, event: AgentProgressEvent) {
|
||||
if let Ok(payload) = serde_json::to_string(&event) {
|
||||
let _ = tx.send(payload);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,6 +153,25 @@ pub async fn find_documents(
|
||||
Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))
|
||||
}
|
||||
|
||||
pub async fn document_find_documents(
|
||||
State(state): State<Arc<WebState>>,
|
||||
Json(req): Json<MongoFindRequest>,
|
||||
) -> Result<Json<serde_json::Value>, AppError> {
|
||||
let result = dbx_core::mongo_ops::document_find_documents_core(
|
||||
&state.app,
|
||||
&req.connection_id,
|
||||
&req.database,
|
||||
&req.collection,
|
||||
req.skip.unwrap_or(0),
|
||||
req.limit.unwrap_or(50),
|
||||
req.filter.as_deref(),
|
||||
req.sort.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(AppError)?;
|
||||
Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))
|
||||
}
|
||||
|
||||
pub async fn aggregate_documents(
|
||||
State(state): State<Arc<WebState>>,
|
||||
Json(req): Json<MongoAggregateRequest>,
|
||||
|
||||
@@ -152,6 +152,7 @@ pub struct RedisCommandRequest {
|
||||
pub connection_id: String,
|
||||
pub db: u32,
|
||||
pub command: String,
|
||||
pub skip_safety_check: Option<bool>,
|
||||
}
|
||||
|
||||
pub async fn list_databases(
|
||||
@@ -438,8 +439,14 @@ pub async fn execute_command(
|
||||
)));
|
||||
}
|
||||
}
|
||||
let result = dbx_core::redis_ops::redis_execute_command_core(&state.app, &req.connection_id, req.db, &req.command)
|
||||
.await
|
||||
.map_err(AppError)?;
|
||||
let result = dbx_core::redis_ops::redis_execute_command_core(
|
||||
&state.app,
|
||||
&req.connection_id,
|
||||
req.db,
|
||||
&req.command,
|
||||
req.skip_safety_check.unwrap_or(false),
|
||||
)
|
||||
.await
|
||||
.map_err(AppError)?;
|
||||
Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))
|
||||
}
|
||||
|
||||
@@ -25,6 +25,12 @@ test("allows MongoDB legacy agent fallback after native driver timeout", () => {
|
||||
assert.equal(connectionAttemptTimeoutMs({ db_type: "mongodb", connect_timeout_secs: 5 }), 5_000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS + MONGO_LEGACY_FALLBACK_TIMEOUT_BUFFER_MS);
|
||||
});
|
||||
|
||||
test("uses a shared minimum timeout for built-in agent drivers", () => {
|
||||
assert.equal(connectionAttemptTimeoutMs({ db_type: "saphana", connect_timeout_secs: 5 }), 15_000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS);
|
||||
assert.equal(connectionAttemptTimeoutMs({ db_type: "db2", connect_timeout_secs: 5 }), 15_000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS);
|
||||
assert.equal(connectionAttemptTimeoutMs({ db_type: "oracle", connect_timeout_secs: 20 }), 20_000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS);
|
||||
});
|
||||
|
||||
test("formats connection attempt timeout messages", () => {
|
||||
assert.match(connectionAttemptTimeoutMessage(7_001), /timed out after 8s/);
|
||||
assert.match(connectionAttemptTimeoutMessage(7_001), /VPN/);
|
||||
|
||||
@@ -18,9 +18,10 @@ function installBrowserTestGlobals() {
|
||||
length: 0,
|
||||
};
|
||||
globalThis.fetch = (async (input, init) => {
|
||||
if (String(input) !== "/api/query/prepare-data-grid-save") {
|
||||
return new Response("unexpected request", { status: 500 });
|
||||
if (String(input) === "/api/history/save") {
|
||||
return new Response("null", { status: 200, headers: { "Content-Type": "application/json" } });
|
||||
}
|
||||
if (String(input) !== "/api/query/prepare-data-grid-save") return new Response("unexpected request", { status: 500 });
|
||||
const body = JSON.parse(String(init?.body ?? "{}"));
|
||||
const options = body.options as DataGridSaveStatementOptions;
|
||||
return new Response(
|
||||
@@ -168,9 +169,11 @@ test("cloning a row copies non-generated primary key values without executing sa
|
||||
primaryKeys: ["code", "year"],
|
||||
})),
|
||||
onExecuteSql: computed(() => undefined),
|
||||
customSave: computed(() => async () => {
|
||||
saveCalls += 1;
|
||||
}),
|
||||
customSaveHandler: computed(() => ({
|
||||
save: async () => {
|
||||
saveCalls += 1;
|
||||
},
|
||||
})),
|
||||
sql: computed(() => undefined),
|
||||
searchText: ref(""),
|
||||
whereFilterInput: ref(""),
|
||||
@@ -247,7 +250,7 @@ test("cloning a row clears auto-generated key columns", async () => {
|
||||
primaryKeys: ["id"],
|
||||
})),
|
||||
onExecuteSql: computed(() => undefined),
|
||||
customSave: computed(() => undefined),
|
||||
customSaveHandler: computed(() => undefined),
|
||||
sql: computed(() => undefined),
|
||||
searchText: ref(""),
|
||||
whereFilterInput: ref(""),
|
||||
@@ -301,7 +304,7 @@ test("saving deleted rows reloads current table data", async () => {
|
||||
primaryKeys: ["id"],
|
||||
})),
|
||||
onExecuteSql: computed(() => undefined),
|
||||
customSave: computed(() => async () => {}),
|
||||
customSaveHandler: computed(() => ({ save: async () => {} })),
|
||||
sql: computed(() => "SELECT id, name FROM people"),
|
||||
searchText: ref("ada"),
|
||||
whereFilterInput: ref("name ILIKE '%a%'"),
|
||||
@@ -360,7 +363,7 @@ test("saving inserted rows reloads current table data", async () => {
|
||||
onExecuteSql: computed(() => async (sql: string) => {
|
||||
executedSql.push(sql);
|
||||
}),
|
||||
customSave: computed(() => undefined),
|
||||
customSaveHandler: computed(() => undefined),
|
||||
sql: computed(() => "SELECT id, name FROM people"),
|
||||
searchText: ref("linus"),
|
||||
whereFilterInput: ref("name ILIKE '%l%'"),
|
||||
@@ -406,7 +409,7 @@ test("saving edited rows without deletes does not reload table data", async () =
|
||||
primaryKeys: ["id"],
|
||||
})),
|
||||
onExecuteSql: computed(() => undefined),
|
||||
customSave: computed(() => async () => {}),
|
||||
customSaveHandler: computed(() => ({ save: async () => {} })),
|
||||
sql: computed(() => "SELECT id, name FROM people"),
|
||||
searchText: ref(""),
|
||||
whereFilterInput: ref(""),
|
||||
@@ -463,7 +466,7 @@ test("saving manually typed JSON from a MySQL grid normalizes smart quotes", asy
|
||||
onExecuteSql: computed(() => async (sql: string) => {
|
||||
executedSql.push(sql);
|
||||
}),
|
||||
customSave: computed(() => undefined),
|
||||
customSaveHandler: computed(() => undefined),
|
||||
sql: computed(() => "SELECT id, payload FROM settings"),
|
||||
searchText: ref(""),
|
||||
whereFilterInput: ref(""),
|
||||
@@ -518,7 +521,7 @@ test("saving manually typed JSON arrays from a Postgres array column uses array
|
||||
onExecuteSql: computed(() => async (sql: string) => {
|
||||
executedSql.push(sql);
|
||||
}),
|
||||
customSave: computed(() => undefined),
|
||||
customSaveHandler: computed(() => undefined),
|
||||
sql: computed(() => "SELECT id, tags FROM articles"),
|
||||
searchText: ref(""),
|
||||
whereFilterInput: ref(""),
|
||||
@@ -595,7 +598,7 @@ test("failed table data save records a failed history entry", async () => {
|
||||
primaryKeys: ["id"],
|
||||
})),
|
||||
onExecuteSql: computed(() => undefined),
|
||||
customSave: computed(() => undefined),
|
||||
customSaveHandler: computed(() => undefined),
|
||||
sql: computed(() => "SELECT id, title FROM pp_questions"),
|
||||
searchText: ref(""),
|
||||
whereFilterInput: ref(""),
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import { test } from "vitest";
|
||||
import { buildDocumentFilterCondition, combineDocumentFilterConditions, currentDocumentFilterJson, documentStoreProviderFor, elasticsearchSearchBodyFromDocumentQuery, type DocumentFilterRule } from "../../apps/desktop/src/lib/documentStoreProvider.ts";
|
||||
|
||||
function rule(patch: Partial<DocumentFilterRule>): DocumentFilterRule {
|
||||
return {
|
||||
id: "rule-1",
|
||||
fieldName: "city",
|
||||
mode: "equals",
|
||||
rawValue: "长治",
|
||||
conjunction: "AND",
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
test("selects MongoDB and Elasticsearch document store providers", () => {
|
||||
assert.equal(documentStoreProviderFor("mongodb").kind, "mongodb");
|
||||
assert.equal(documentStoreProviderFor("elasticsearch").kind, "elasticsearch");
|
||||
});
|
||||
|
||||
test("providers build store-specific query previews", () => {
|
||||
const t = ((key: string, params?: Record<string, unknown>) => `${key}:${params?.count ?? ""}`) as never;
|
||||
const mongo = documentStoreProviderFor("mongodb");
|
||||
const elasticsearch = documentStoreProviderFor("elasticsearch");
|
||||
|
||||
assert.equal(mongo.documentsLabel({ total: 7, t }), "mongo.documents:7");
|
||||
assert.equal(mongo.queryPreview({ collection: "orders", filterJson: '{"city":"长治"}', sortJson: '{"createdAt":-1}', skip: 20, limit: 10 }), 'db.orders.find({"city":"长治"}).sort({"createdAt":-1}).skip(20).limit(10)');
|
||||
assert.equal(elasticsearch.documentsLabel({ total: 7, t }), "Documents");
|
||||
assert.equal(elasticsearch.filterInputLabel, "filter");
|
||||
assert.equal(
|
||||
elasticsearch.queryPreview({ collection: "orders", filterJson: '{"city":"长治"}', sortJson: '{"createdAt":-1}', skip: 20, limit: 10 }),
|
||||
["POST /orders/_search", "{", ' "from": 20,', ' "size": 10,', ' "query": {', ' "term": {', ' "city": "长治"', " }", " },", ' "sort": [', " {", ' "createdAt": {', ' "order": "desc"', " }", " }", " ]", "}"].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
test("builds reusable document filter conditions", () => {
|
||||
assert.deepEqual(buildDocumentFilterCondition(rule({})), { city: "长治" });
|
||||
assert.deepEqual(buildDocumentFilterCondition(rule({ mode: "not-like", rawValue: "test" })), {
|
||||
city: { $not: { $regex: "test", $options: "i" } },
|
||||
});
|
||||
assert.deepEqual(buildDocumentFilterCondition(rule({ mode: "is-not-null", rawValue: "" })), { city: { $ne: null } });
|
||||
});
|
||||
|
||||
test("combines manual and structured document filters", () => {
|
||||
const structured = combineDocumentFilterConditions([{ city: "长治" }, { status: "active" }], [rule({}), rule({ fieldName: "status", rawValue: "active", conjunction: "OR" })]);
|
||||
|
||||
assert.deepEqual(structured, { $or: [{ city: "长治" }, { status: "active" }] });
|
||||
assert.equal(currentDocumentFilterJson('{"tenant":"a"}', structured), JSON.stringify({ $and: [{ tenant: "a" }, structured] }));
|
||||
});
|
||||
|
||||
test("translates document filters to Elasticsearch search body previews", () => {
|
||||
assert.deepEqual(
|
||||
elasticsearchSearchBodyFromDocumentQuery({
|
||||
filterJson: JSON.stringify({ $and: [{ city: { $ne: "上海" } }, { age: { $gt: 18, $lte: 60 } }] }),
|
||||
sortJson: '{"createdAt":-1}',
|
||||
skip: 0,
|
||||
limit: 50,
|
||||
}),
|
||||
{
|
||||
from: 0,
|
||||
size: 50,
|
||||
query: {
|
||||
bool: {
|
||||
filter: [{ bool: { must_not: [{ term: { city: "上海" } }] } }, { range: { age: { gt: 18, lte: 60 } } }],
|
||||
},
|
||||
},
|
||||
sort: [{ createdAt: { order: "desc" } }],
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -15,6 +15,11 @@ function conn(id: string, name?: string): ConnectionConfig {
|
||||
};
|
||||
}
|
||||
|
||||
function groupConnectionIds(entry: SidebarLayout["order"][number]): string[] {
|
||||
assert.equal(entry.type, "group");
|
||||
return (entry.children ?? []).filter((child) => child.type === "connection").map((child) => child.id);
|
||||
}
|
||||
|
||||
// --- reconcileLayout ---
|
||||
|
||||
test("reconcileLayout returns all connections ungrouped when layout is null", () => {
|
||||
@@ -48,7 +53,7 @@ test("reconcileLayout removes stale connections from layout", () => {
|
||||
const result = reconcileLayout(["a", "b"], layout);
|
||||
const groupEntry = result.order.find((e) => e.type === "group");
|
||||
assert.ok(groupEntry && groupEntry.type === "group");
|
||||
assert.deepEqual(groupEntry.connectionIds, ["a"]);
|
||||
assert.deepEqual(groupConnectionIds(groupEntry), ["a"]);
|
||||
assert.equal(result.order.length, 2);
|
||||
});
|
||||
|
||||
@@ -161,7 +166,7 @@ test("moveConnectionToGroup moves connection into a group", () => {
|
||||
const result = moveConnectionToGroup(layout, "a", "g1");
|
||||
const groupEntry = result.order.find((e) => e.type === "group" && e.id === "g1");
|
||||
assert.ok(groupEntry && groupEntry.type === "group");
|
||||
assert.deepEqual(groupEntry.connectionIds, ["a"]);
|
||||
assert.deepEqual(groupConnectionIds(groupEntry), ["a"]);
|
||||
assert.equal(result.order.length, 1);
|
||||
});
|
||||
|
||||
@@ -221,7 +226,7 @@ test("reorderEntry moves connection inside a group", () => {
|
||||
assert.equal(result.order.length, 1);
|
||||
const groupEntry = result.order[0];
|
||||
assert.ok(groupEntry.type === "group");
|
||||
assert.deepEqual(groupEntry.connectionIds, ["a"]);
|
||||
assert.deepEqual(groupConnectionIds(groupEntry), ["a"]);
|
||||
});
|
||||
|
||||
test("reorderEntry is a no-op when dragging to same position", () => {
|
||||
@@ -251,7 +256,7 @@ test("appendConnectionToLayout adds to target group and expands it", () => {
|
||||
|
||||
assert.equal(result.groups[0].collapsed, false);
|
||||
assert.ok(groupEntry.type === "group");
|
||||
assert.deepEqual(groupEntry.connectionIds, ["a", "b"]);
|
||||
assert.deepEqual(groupConnectionIds(groupEntry), ["a", "b"]);
|
||||
});
|
||||
|
||||
test("removeConnectionFromSidebarLayout removes from ungrouped", () => {
|
||||
@@ -268,5 +273,5 @@ test("removeConnectionFromSidebarLayout removes from inside a group", () => {
|
||||
const result = removeConnectionFromSidebarLayout(layout, "a");
|
||||
const groupEntry = result.order[0];
|
||||
assert.ok(groupEntry.type === "group");
|
||||
assert.deepEqual(groupEntry.connectionIds, ["b"]);
|
||||
assert.deepEqual(groupConnectionIds(groupEntry), ["b"]);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "vitest";
|
||||
import { buildTreeNodesFromLayout, deleteGroup, moveConnectionToGroup, reconcileLayout, reorderEntry } from "../../apps/desktop/src/lib/sidebarLayout.ts";
|
||||
import type { ConnectionConfig, SidebarLayout } from "../../apps/desktop/src/types/database.ts";
|
||||
|
||||
function conn(id: string): ConnectionConfig {
|
||||
return {
|
||||
id,
|
||||
name: id,
|
||||
db_type: "mysql",
|
||||
host: "localhost",
|
||||
port: 3306,
|
||||
username: "root",
|
||||
password: "",
|
||||
};
|
||||
}
|
||||
|
||||
test("reconciles legacy grouped layout into nested children", () => {
|
||||
const layout: SidebarLayout = {
|
||||
groups: [{ id: "g1", name: "Group", collapsed: false }],
|
||||
order: [{ type: "group", id: "g1", connectionIds: ["c1"] }],
|
||||
};
|
||||
|
||||
const reconciled = reconcileLayout(["c1", "c2"], layout);
|
||||
|
||||
assert.deepEqual(reconciled.order, [
|
||||
{ type: "group", id: "g1", children: [{ type: "connection", id: "c1" }] },
|
||||
{ type: "connection", id: "c2" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("builds nested connection group tree nodes", () => {
|
||||
const layout: SidebarLayout = {
|
||||
groups: [
|
||||
{ id: "g1", name: "Parent", collapsed: false },
|
||||
{ id: "g2", name: "Child", collapsed: false },
|
||||
],
|
||||
order: [
|
||||
{
|
||||
type: "group",
|
||||
id: "g1",
|
||||
children: [{ type: "group", id: "g2", children: [{ type: "connection", id: "c1" }] }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const nodes = buildTreeNodesFromLayout(layout, [conn("c1")], new Set());
|
||||
|
||||
assert.deepEqual(
|
||||
nodes.map((node) => [node.type, node.label, node.children?.[0]?.type, node.children?.[0]?.children?.[0]?.id]),
|
||||
[["connection-group", "Parent", "connection-group", "c1"]],
|
||||
);
|
||||
});
|
||||
|
||||
test("moves connections and groups into nested groups", () => {
|
||||
const layout: SidebarLayout = {
|
||||
groups: [
|
||||
{ id: "g1", name: "Parent", collapsed: false },
|
||||
{ id: "g2", name: "Child", collapsed: false },
|
||||
],
|
||||
order: [
|
||||
{ type: "group", id: "g1", children: [] },
|
||||
{ type: "group", id: "g2", children: [] },
|
||||
{ type: "connection", id: "c1" },
|
||||
],
|
||||
};
|
||||
|
||||
const withNestedGroup = reorderEntry(layout, "g2", "g1", "inside");
|
||||
const withNestedConnection = moveConnectionToGroup(withNestedGroup, "c1", "g2");
|
||||
|
||||
assert.deepEqual(withNestedConnection.order, [
|
||||
{
|
||||
type: "group",
|
||||
id: "g1",
|
||||
children: [{ type: "group", id: "g2", children: [{ type: "connection", id: "c1" }] }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("deleting a parent group keeps nested child groups", () => {
|
||||
const layout: SidebarLayout = {
|
||||
groups: [
|
||||
{ id: "g1", name: "Parent", collapsed: false },
|
||||
{ id: "g2", name: "Child", collapsed: false },
|
||||
],
|
||||
order: [{ type: "group", id: "g1", children: [{ type: "group", id: "g2", children: [{ type: "connection", id: "c1" }] }] }],
|
||||
};
|
||||
|
||||
const next = deleteGroup(layout, "g1");
|
||||
|
||||
assert.deepEqual(next.groups, [{ id: "g2", name: "Child", collapsed: false }]);
|
||||
assert.deepEqual(next.order, [{ type: "group", id: "g2", children: [{ type: "connection", id: "c1" }] }]);
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
buildSqlCompletionItems,
|
||||
getSqlFunctionSignatureHelp,
|
||||
getSqlCompletionResultValidFor,
|
||||
isSqlCommentContext,
|
||||
shouldAutoOpenSqlCompletion,
|
||||
extractCteDefinitions,
|
||||
getSqlCompletionContext,
|
||||
@@ -520,6 +521,22 @@ test("does not auto-open completion after structural punctuation", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("does not auto-open completion inside SQL comments", () => {
|
||||
for (const { sql, cursor } of [
|
||||
{ sql: "-- sougou", cursor: "-- sougou".length },
|
||||
{ sql: "select 1 -- sougou", cursor: "select 1 -- sougou".length },
|
||||
{ sql: "# sougou", cursor: "# sougou".length },
|
||||
{ sql: "select /* sougou */ 1", cursor: "select /* sougou".length },
|
||||
{ sql: "select /* sougou", cursor: "select /* sougou".length },
|
||||
]) {
|
||||
assert.equal(shouldAutoOpenSqlCompletion(sql, cursor), false, sql);
|
||||
}
|
||||
assert.equal(isSqlCommentContext("select '-- not comment' as value", "select '-- not comment'".length), false);
|
||||
assert.equal(isSqlCommentContext("select /* comment */ val", "select /* comment */ val".length), false);
|
||||
assert.equal(shouldAutoOpenSqlCompletion("select '-- not comment' as value", "select '-- not comment' as value".length), true);
|
||||
assert.equal(shouldAutoOpenSqlCompletion("select /* comment */ val", "select /* comment */ val".length), true);
|
||||
});
|
||||
|
||||
test("auto-opens completion after word characters and explicit dot qualifiers", () => {
|
||||
for (const sql of ["sel", "select * from us", "select u."]) {
|
||||
assert.equal(shouldAutoOpenSqlCompletion(sql, sql.length), true, sql);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import { test } from "vitest";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { executionSummaryItems, tabDisplayTitle, tabularResultItems } from "../../apps/desktop/src/lib/tabPresentation.ts";
|
||||
import { databaseDisplayNameForTab, executionSummaryItems, tabDisplayTitle, tabularResultItems } from "../../apps/desktop/src/lib/tabPresentation.ts";
|
||||
import { useConnectionStore } from "../../apps/desktop/src/stores/connectionStore.ts";
|
||||
import type { ConnectionConfig, QueryResult, QueryTab } from "../../apps/desktop/src/types/database.ts";
|
||||
|
||||
@@ -71,6 +71,39 @@ test("query tab display title uses custom title when present", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("jdbc tabs use the connection target when database is empty", () => {
|
||||
const restoreStorage = installMemoryStorage();
|
||||
setActivePinia(createPinia());
|
||||
useConnectionStore().addEphemeralConnection({
|
||||
...conn("conn-1"),
|
||||
db_type: "jdbc",
|
||||
connection_string: "jdbc:oracle:thin:@172.20.66.143:20001:XE",
|
||||
});
|
||||
const t = (key: string) => (key === "editor.noDatabase" ? "No database selected" : key);
|
||||
|
||||
try {
|
||||
assert.equal(databaseDisplayNameForTab("conn-1", "", t), "XE");
|
||||
assert.equal(
|
||||
tabDisplayTitle(
|
||||
queryTab({
|
||||
database: "",
|
||||
mode: "data",
|
||||
tableMeta: {
|
||||
schema: "SYSTEM",
|
||||
tableName: "DBX_JDBC_TEST",
|
||||
columns: [],
|
||||
primaryKeys: ["ID"],
|
||||
},
|
||||
}),
|
||||
t,
|
||||
),
|
||||
"DBX_JDBC_TEST@XE.SYSTEM",
|
||||
);
|
||||
} finally {
|
||||
restoreStorage();
|
||||
}
|
||||
});
|
||||
|
||||
test("tabular result items hide statement results without returned columns", () => {
|
||||
const results = [result([]), result(["id"]), result([]), result(["name"])];
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "vitest";
|
||||
import { buildStructureTargetLabel, combineDataTypeForDatabase, createColumnDrafts, createIndexDrafts, getDataTypeOptions, normalizeDataTypeParams, parseExtraToColumnExtra, toColumnNames } from "../../apps/desktop/src/lib/tableStructureEditorState.ts";
|
||||
import { buildStructureTargetLabel, combineDataTypeForDatabase, createColumnDrafts, createIndexDrafts, generateIndexName, generateUniqueIndexName, getDataTypeOptions, normalizeDataTypeParams, parseExtraToColumnExtra, toColumnNames } from "../../apps/desktop/src/lib/tableStructureEditorState.ts";
|
||||
import type { ColumnInfo, IndexInfo } from "../../apps/desktop/src/types/database.ts";
|
||||
|
||||
const columns: ColumnInfo[] = [
|
||||
@@ -153,6 +153,17 @@ test("creates editable index drafts and splits pasted column lists", () => {
|
||||
assert.equal(toColumnNames(["id", "name"]), "id, name");
|
||||
});
|
||||
|
||||
test("generates conventional index names from table and columns", () => {
|
||||
assert.equal(generateIndexName("A", ["B"]), "A_B_IDX");
|
||||
assert.equal(generateIndexName("order item", ["customer-id", "created_at"]), "ORDER_ITEM_CUSTOMER_ID_CREATED_AT_IDX");
|
||||
assert.equal(generateIndexName("users", ["email"], 12), "USERS_EM_IDX");
|
||||
});
|
||||
|
||||
test("generates unique index names when automatic name already exists", () => {
|
||||
assert.equal(generateUniqueIndexName("users", ["email"], ["USERS_EMAIL_IDX"]), "USERS_EMAIL_IDX_2");
|
||||
assert.equal(generateUniqueIndexName("users", ["email"], ["users_email_idx", "USERS_EMAIL_IDX_2"]), "USERS_EMAIL_IDX_3");
|
||||
});
|
||||
|
||||
test("structure editor target label omits duplicate database and schema", () => {
|
||||
assert.equal(buildStructureTargetLabel("online-clickhouse", "testdb", "testdb", "users"), "online-clickhouse / testdb / users");
|
||||
assert.equal(buildStructureTargetLabel("online-postgres", "app", "public", "users"), "online-postgres / app / public / users");
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
|
||||
|
||||
if [ -n "${DBX_JAVA_BIN:-}" ] && [ -x "$DBX_JAVA_BIN" ]; then
|
||||
JAVA_BIN="$DBX_JAVA_BIN"
|
||||
elif [ -n "${JAVA_HOME:-}" ] && [ -x "$JAVA_HOME/bin/java" ]; then
|
||||
JAVA_BIN="$JAVA_HOME/bin/java"
|
||||
elif [ -x "/opt/homebrew/opt/openjdk/bin/java" ]; then
|
||||
JAVA_BIN="/opt/homebrew/opt/openjdk/bin/java"
|
||||
elif [ -x "/usr/local/opt/openjdk/bin/java" ]; then
|
||||
JAVA_BIN="/usr/local/opt/openjdk/bin/java"
|
||||
elif command -v java >/dev/null 2>&1 && java -version >/dev/null 2>&1; then
|
||||
JAVA_BIN="java"
|
||||
else
|
||||
echo "Java runtime not found. Install Java or the optional DBX JDBC runtime." >&2
|
||||
exit 127
|
||||
fi
|
||||
|
||||
exec "$JAVA_BIN" \
|
||||
-Dfile.encoding=UTF-8 \
|
||||
-Dsun.stdout.encoding=UTF-8 \
|
||||
-Dsun.stderr.encoding=UTF-8 \
|
||||
-cp "$DIR/../lib/dbx-jdbc-plugin.jar" \
|
||||
app.dbx.jdbc.maven.DbxMavenResolver "$@"
|
||||
@@ -0,0 +1,31 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
if defined DBX_JAVA_BIN (
|
||||
if exist "%DBX_JAVA_BIN%" (
|
||||
set "JAVA_BIN=%DBX_JAVA_BIN%"
|
||||
goto :run
|
||||
)
|
||||
)
|
||||
|
||||
if defined JAVA_HOME (
|
||||
if exist "%JAVA_HOME%\bin\java.exe" (
|
||||
set "JAVA_BIN=%JAVA_HOME%\bin\java.exe"
|
||||
goto :run
|
||||
)
|
||||
)
|
||||
|
||||
where java >nul 2>nul
|
||||
if %errorlevel% equ 0 (
|
||||
java -version >nul 2>nul
|
||||
if %errorlevel% equ 0 (
|
||||
set "JAVA_BIN=java"
|
||||
goto :run
|
||||
)
|
||||
)
|
||||
|
||||
echo Java runtime not found. Install Java or the optional DBX JDBC runtime. >&2
|
||||
exit /b 127
|
||||
|
||||
:run
|
||||
"%JAVA_BIN%" -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -cp "%~dp0..\lib\dbx-jdbc-plugin.jar" app.dbx.jdbc.maven.DbxMavenResolver %*
|
||||
@@ -15,8 +15,11 @@ mkdir -p "$PACKAGE_DIR/bin" "$PACKAGE_DIR/lib"
|
||||
cp "$ROOT/manifest.json" "$PACKAGE_DIR/manifest.json"
|
||||
cp "$ROOT/bin/dbx-jdbc-plugin" "$PACKAGE_DIR/bin/dbx-jdbc-plugin"
|
||||
cp "$ROOT/bin/dbx-jdbc-plugin.bat" "$PACKAGE_DIR/bin/dbx-jdbc-plugin.bat"
|
||||
cp "$ROOT/bin/dbx-maven-resolver" "$PACKAGE_DIR/bin/dbx-maven-resolver"
|
||||
cp "$ROOT/bin/dbx-maven-resolver.bat" "$PACKAGE_DIR/bin/dbx-maven-resolver.bat"
|
||||
cp "$ROOT/target/dbx-jdbc-plugin-$VERSION-all.jar" "$PACKAGE_DIR/lib/dbx-jdbc-plugin.jar"
|
||||
chmod +x "$PACKAGE_DIR/bin/dbx-jdbc-plugin"
|
||||
chmod +x "$PACKAGE_DIR/bin/dbx-maven-resolver"
|
||||
|
||||
(cd "$ROOT/dist" && zip -qr "dbx-jdbc-plugin-$VERSION.zip" "dbx-jdbc-plugin-$VERSION")
|
||||
cp "$ZIP_PATH" "$LATEST_ZIP_PATH"
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.resolver.version>2.0.18</maven.resolver.version>
|
||||
<maven.core.version>4.0.0-rc-5</maven.core.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -33,6 +35,56 @@
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.18.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.resolver</groupId>
|
||||
<artifactId>maven-resolver-api</artifactId>
|
||||
<version>${maven.resolver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.resolver</groupId>
|
||||
<artifactId>maven-resolver-spi</artifactId>
|
||||
<version>${maven.resolver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.resolver</groupId>
|
||||
<artifactId>maven-resolver-util</artifactId>
|
||||
<version>${maven.resolver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.resolver</groupId>
|
||||
<artifactId>maven-resolver-impl</artifactId>
|
||||
<version>${maven.resolver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.resolver</groupId>
|
||||
<artifactId>maven-resolver-connector-basic</artifactId>
|
||||
<version>${maven.resolver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.resolver</groupId>
|
||||
<artifactId>maven-resolver-transport-file</artifactId>
|
||||
<version>${maven.resolver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.resolver</groupId>
|
||||
<artifactId>maven-resolver-transport-jdk</artifactId>
|
||||
<version>${maven.resolver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.resolver</groupId>
|
||||
<artifactId>maven-resolver-supplier-mvn4</artifactId>
|
||||
<version>${maven.resolver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven</groupId>
|
||||
<artifactId>maven-resolver-provider</artifactId>
|
||||
<version>${maven.core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven</groupId>
|
||||
<artifactId>maven-model-builder</artifactId>
|
||||
<version>${maven.core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
package app.dbx.jdbc.maven;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.eclipse.aether.RepositorySystem;
|
||||
import org.eclipse.aether.RepositorySystemSession;
|
||||
import org.eclipse.aether.artifact.Artifact;
|
||||
import org.eclipse.aether.artifact.DefaultArtifact;
|
||||
import org.eclipse.aether.collection.CollectRequest;
|
||||
import org.eclipse.aether.graph.Dependency;
|
||||
import org.eclipse.aether.graph.DependencyNode;
|
||||
import org.eclipse.aether.repository.LocalRepository;
|
||||
import org.eclipse.aether.repository.RemoteRepository;
|
||||
import org.eclipse.aether.resolution.DependencyRequest;
|
||||
import org.eclipse.aether.resolution.DependencyResult;
|
||||
import org.eclipse.aether.supplier.RepositorySystemSupplier;
|
||||
import org.eclipse.aether.supplier.SessionBuilderSupplier;
|
||||
import org.eclipse.aether.util.artifact.JavaScopes;
|
||||
import org.eclipse.aether.util.filter.DependencyFilterUtils;
|
||||
|
||||
public final class DbxMavenResolver {
|
||||
private static final String DEFAULT_REPOSITORY = "https://repo.maven.apache.org/maven2/";
|
||||
private static final ObjectMapper JSON = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
|
||||
|
||||
private DbxMavenResolver() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
try {
|
||||
ResolverOptions options = ResolverOptions.parse(args);
|
||||
ResolveResult result = resolve(options);
|
||||
JSON.writeValue(System.out, result);
|
||||
System.out.println();
|
||||
} catch (Exception err) {
|
||||
Map<String, String> error = new LinkedHashMap<>();
|
||||
error.put("error", err.getMessage() == null ? err.getClass().getSimpleName() : err.getMessage());
|
||||
JSON.writeValue(System.err, error);
|
||||
System.err.println();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static ResolveResult resolve(ResolverOptions options) throws Exception {
|
||||
RepositorySystem system = new RepositorySystemSupplier().get();
|
||||
RepositorySystemSession session = new SessionBuilderSupplier(system)
|
||||
.get()
|
||||
.withLocalRepositories(new LocalRepository(options.localRepository))
|
||||
.setRepositoryListener(null)
|
||||
.setTransferListener(null)
|
||||
.build();
|
||||
|
||||
Artifact rootArtifact = parseCoordinate(options.coordinate);
|
||||
Dependency root = new Dependency(rootArtifact, options.scope);
|
||||
CollectRequest collect = new CollectRequest();
|
||||
collect.setRoot(root);
|
||||
for (int index = 0; index < options.repositories.size(); index++) {
|
||||
collect.addRepository(new RemoteRepository.Builder("repo-" + index, "default", options.repositories.get(index)).build());
|
||||
}
|
||||
|
||||
DependencyRequest request = new DependencyRequest(collect, DependencyFilterUtils.classpathFilter(options.scope));
|
||||
DependencyResult dependencyResult = system.resolveDependencies(session, request);
|
||||
List<ResolvedArtifact> artifacts = new ArrayList<>();
|
||||
collectRuntimeArtifacts(dependencyResult.getRoot(), true, artifacts);
|
||||
return new ResolveResult(options.coordinate, options.scope, options.repositories, artifacts);
|
||||
}
|
||||
|
||||
private static void collectRuntimeArtifacts(DependencyNode node, boolean root, List<ResolvedArtifact> artifacts) throws Exception {
|
||||
Dependency dependency = node.getDependency();
|
||||
if (!root && dependency != null && !isRuntimeDependency(dependency)) {
|
||||
return;
|
||||
}
|
||||
Artifact artifact = node.getArtifact();
|
||||
if (artifact != null && artifact.getFile() != null) {
|
||||
artifacts.add(ResolvedArtifact.from(artifact, artifact.getFile()));
|
||||
}
|
||||
for (DependencyNode child : node.getChildren()) {
|
||||
collectRuntimeArtifacts(child, false, artifacts);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isRuntimeDependency(Dependency dependency) {
|
||||
if (dependency.isOptional()) {
|
||||
return false;
|
||||
}
|
||||
String scope = dependency.getScope();
|
||||
return scope == null || scope.isBlank() || JavaScopes.COMPILE.equals(scope) || JavaScopes.RUNTIME.equals(scope);
|
||||
}
|
||||
|
||||
private static Artifact parseCoordinate(String coordinate) {
|
||||
String trimmed = coordinate == null ? "" : coordinate.trim();
|
||||
if (trimmed.isEmpty()) {
|
||||
throw new IllegalArgumentException("Maven coordinate is required");
|
||||
}
|
||||
String[] parts = trimmed.split(":");
|
||||
if (parts.length == 3) {
|
||||
return new DefaultArtifact(parts[0], parts[1], "", "jar", parts[2]);
|
||||
}
|
||||
if (parts.length == 4) {
|
||||
return new DefaultArtifact(parts[0], parts[1], parts[3], "jar", parts[2]);
|
||||
}
|
||||
if (parts.length == 5) {
|
||||
return new DefaultArtifact(parts[0], parts[1], parts[3], parts[2], parts[4]);
|
||||
}
|
||||
return new DefaultArtifact(trimmed);
|
||||
}
|
||||
|
||||
private static String sha256(File file) throws Exception {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] bytes = java.nio.file.Files.readAllBytes(file.toPath());
|
||||
byte[] hash = digest.digest(bytes);
|
||||
StringBuilder value = new StringBuilder(hash.length * 2);
|
||||
for (byte b : hash) {
|
||||
value.append(String.format("%02x", b));
|
||||
}
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
private static final class ResolverOptions {
|
||||
private String coordinate;
|
||||
private String scope = JavaScopes.RUNTIME;
|
||||
private Path localRepository = Path.of(System.getProperty("user.home"), ".dbx", "maven");
|
||||
private final List<String> repositories = new ArrayList<>();
|
||||
|
||||
private static ResolverOptions parse(String[] args) {
|
||||
ResolverOptions options = new ResolverOptions();
|
||||
for (int index = 0; index < args.length; index++) {
|
||||
String arg = args[index];
|
||||
switch (arg) {
|
||||
case "resolve" -> {
|
||||
}
|
||||
case "--coordinate", "-c" -> options.coordinate = value(args, ++index, arg);
|
||||
case "--scope" -> options.scope = value(args, ++index, arg).toLowerCase(Locale.ROOT);
|
||||
case "--repo", "--repository" -> options.repositories.add(value(args, ++index, arg));
|
||||
case "--local-repo" -> options.localRepository = Path.of(value(args, ++index, arg));
|
||||
default -> {
|
||||
if (arg.startsWith("-")) {
|
||||
throw new IllegalArgumentException("Unsupported option: " + arg);
|
||||
}
|
||||
if (options.coordinate == null) {
|
||||
options.coordinate = arg;
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unexpected argument: " + arg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (options.repositories.isEmpty()) {
|
||||
options.repositories.add(DEFAULT_REPOSITORY);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
private static String value(String[] args, int index, String option) {
|
||||
if (index >= args.length || args[index].isBlank()) {
|
||||
throw new IllegalArgumentException(option + " requires a value");
|
||||
}
|
||||
return args[index];
|
||||
}
|
||||
}
|
||||
|
||||
public record ResolveResult(
|
||||
String coordinate,
|
||||
String scope,
|
||||
List<String> repositories,
|
||||
List<ResolvedArtifact> artifacts
|
||||
) {
|
||||
}
|
||||
|
||||
public record ResolvedArtifact(
|
||||
String groupId,
|
||||
String artifactId,
|
||||
String version,
|
||||
String classifier,
|
||||
String extension,
|
||||
String file,
|
||||
long size,
|
||||
String sha256
|
||||
) {
|
||||
private static ResolvedArtifact from(Artifact artifact, File file) throws Exception {
|
||||
return new ResolvedArtifact(
|
||||
artifact.getGroupId(),
|
||||
artifact.getArtifactId(),
|
||||
artifact.getVersion(),
|
||||
artifact.getClassifier(),
|
||||
artifact.getExtension(),
|
||||
file.getAbsolutePath(),
|
||||
file.length(),
|
||||
DbxMavenResolver.sha256(file)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,31 @@ pub async fn mongo_find_documents(
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn document_find_documents(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
connection_id: String,
|
||||
database: String,
|
||||
collection: String,
|
||||
skip: u64,
|
||||
limit: i64,
|
||||
filter: Option<String>,
|
||||
sort: Option<String>,
|
||||
) -> Result<MongoDocumentResult, String> {
|
||||
dbx_core::mongo_ops::document_find_documents_core(
|
||||
&state,
|
||||
&connection_id,
|
||||
&database,
|
||||
&collection,
|
||||
skip,
|
||||
limit,
|
||||
filter.as_deref(),
|
||||
sort.as_deref(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mongo_aggregate_documents(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use std::sync::Arc;
|
||||
use tauri::State;
|
||||
use tauri::{Emitter, State};
|
||||
|
||||
use dbx_core::jdbc::{self, JdbcDriverInfo, JdbcPluginStatus};
|
||||
use dbx_core::agent_service::AgentProgressEvent;
|
||||
use dbx_core::jdbc::{self, JdbcDriverInfo, JdbcMavenBundleInfo, JdbcMavenInstallRequest, JdbcPluginStatus};
|
||||
use dbx_core::plugins::InstalledPlugin;
|
||||
|
||||
use super::connection::AppState;
|
||||
@@ -20,8 +21,15 @@ pub async fn jdbc_plugin_status(state: State<'_, Arc<AppState>>) -> Result<JdbcP
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn install_jdbc_plugin(state: State<'_, Arc<AppState>>) -> Result<JdbcPluginStatus, String> {
|
||||
jdbc::install_jdbc_plugin(state.plugins.root_dir()).await
|
||||
pub async fn install_jdbc_plugin(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, Arc<AppState>>,
|
||||
) -> Result<JdbcPluginStatus, String> {
|
||||
let app_handle = app.clone();
|
||||
jdbc::install_jdbc_plugin_with_progress(state.plugins.root_dir(), move |event| {
|
||||
emit_agent_progress(&app_handle, event);
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -48,6 +56,22 @@ pub async fn list_jdbc_drivers(state: State<'_, Arc<AppState>>) -> Result<Vec<Jd
|
||||
.map_err(|err| err.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn list_jdbc_maven_bundles(state: State<'_, Arc<AppState>>) -> Result<Vec<JdbcMavenBundleInfo>, String> {
|
||||
let root_dir = state.plugins.root_dir().to_path_buf();
|
||||
tauri::async_runtime::spawn_blocking(move || jdbc::list_jdbc_maven_bundles(&root_dir))
|
||||
.await
|
||||
.map_err(|err| err.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn install_jdbc_driver_from_maven(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
request: JdbcMavenInstallRequest,
|
||||
) -> Result<Vec<JdbcDriverInfo>, String> {
|
||||
jdbc::install_jdbc_driver_from_maven(state.plugins.root_dir(), request).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn import_jdbc_drivers(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
@@ -66,3 +90,18 @@ pub async fn delete_jdbc_driver(state: State<'_, Arc<AppState>>, path: String) -
|
||||
.await
|
||||
.map_err(|err| err.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn delete_jdbc_maven_bundle(
|
||||
state: State<'_, Arc<AppState>>,
|
||||
bundle_id: String,
|
||||
) -> Result<Vec<JdbcDriverInfo>, String> {
|
||||
let root_dir = state.plugins.root_dir().to_path_buf();
|
||||
tauri::async_runtime::spawn_blocking(move || jdbc::delete_jdbc_maven_bundle(&root_dir, &bundle_id))
|
||||
.await
|
||||
.map_err(|err| err.to_string())?
|
||||
}
|
||||
|
||||
fn emit_agent_progress(app: &tauri::AppHandle, event: AgentProgressEvent) {
|
||||
let _ = app.emit("agent-install-progress", event);
|
||||
}
|
||||
|
||||
@@ -257,6 +257,7 @@ pub async fn redis_execute_command(
|
||||
connection_id: String,
|
||||
db: u32,
|
||||
command: String,
|
||||
skip_safety_check: Option<bool>,
|
||||
) -> Result<RedisCommandResult, String> {
|
||||
// In read-only mode, only allow safe read commands through the raw command interface
|
||||
if let Some(name) = dbx_core::query::connection_readonly_name(&state, &connection_id).await {
|
||||
@@ -268,7 +269,14 @@ pub async fn redis_execute_command(
|
||||
));
|
||||
}
|
||||
}
|
||||
dbx_core::redis_ops::redis_execute_command_core(&state, &connection_id, db, &command).await
|
||||
dbx_core::redis_ops::redis_execute_command_core(
|
||||
&state,
|
||||
&connection_id,
|
||||
db,
|
||||
&command,
|
||||
skip_safety_check.unwrap_or(false),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
@@ -103,7 +103,12 @@ fn sync_saved_sql_directory_blocking(target_dir: &Path, entries: &[SavedSqlSyncE
|
||||
for entry in entries {
|
||||
let mut file_dir = sync_root.to_path_buf();
|
||||
if let Some(folder_name) = entry.folder_name.as_deref().map(str::trim).filter(|name| !name.is_empty()) {
|
||||
file_dir.push(sanitize_file_segment(folder_name));
|
||||
for segment in folder_name.split('/') {
|
||||
let segment = segment.trim();
|
||||
if !segment.is_empty() {
|
||||
file_dir.push(sanitize_file_segment(segment));
|
||||
}
|
||||
}
|
||||
}
|
||||
std::fs::create_dir_all(&file_dir).map_err(|e| e.to_string())?;
|
||||
|
||||
|
||||
@@ -349,8 +349,11 @@ pub fn run() {
|
||||
commands::connection::load_sidebar_layout,
|
||||
commands::plugins::list_plugins,
|
||||
commands::plugins::list_jdbc_drivers,
|
||||
commands::plugins::list_jdbc_maven_bundles,
|
||||
commands::plugins::import_jdbc_drivers,
|
||||
commands::plugins::install_jdbc_driver_from_maven,
|
||||
commands::plugins::delete_jdbc_driver,
|
||||
commands::plugins::delete_jdbc_maven_bundle,
|
||||
commands::plugins::jdbc_plugin_status,
|
||||
commands::plugins::install_jdbc_plugin,
|
||||
commands::plugins::install_jdbc_plugin_local,
|
||||
@@ -477,6 +480,7 @@ pub fn run() {
|
||||
commands::saved_sql::sync_saved_sql_directory,
|
||||
commands::mongo_cmd::mongo_list_databases,
|
||||
commands::mongo_cmd::mongo_list_collections,
|
||||
commands::mongo_cmd::document_find_documents,
|
||||
commands::mongo_cmd::mongo_find_documents,
|
||||
commands::mongo_cmd::mongo_aggregate_documents,
|
||||
commands::mongo_cmd::mongo_insert_document,
|
||||
|
||||
Reference in New Issue
Block a user