diff --git a/apps/desktop/src/components/config/DriverInstallProgressCircle.vue b/apps/desktop/src/components/config/DriverInstallProgressCircle.vue index 8eced5e8c4..96cd0b8e02 100644 --- a/apps/desktop/src/components/config/DriverInstallProgressCircle.vue +++ b/apps/desktop/src/components/config/DriverInstallProgressCircle.vue @@ -12,7 +12,7 @@ const props = defineProps<{ - {{ props.percent ?? "..." }} + {{ props.percent ?? 0 }} diff --git a/apps/desktop/src/components/config/DriverStoreDialog.vue b/apps/desktop/src/components/config/DriverStoreDialog.vue index 388efaafd4..98816a99fa 100644 --- a/apps/desktop/src/components/config/DriverStoreDialog.vue +++ b/apps/desktop/src/components/config/DriverStoreDialog.vue @@ -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(null); const installedJres = computed(() => { const jreMap = new Map(); @@ -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([]); +const jdbcMavenBundles = ref([]); const jdbcDriverSearch = ref(""); const isLoadingJdbcDrivers = ref(false); const jdbcPluginStatus = ref(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(() => { + 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) => {

+ {{ jdbcPluginStatus.compatible @@ -1007,26 +1112,50 @@ watch(driverStoreTab, (tab) => { {{ t("settings.jdbcImport") }}
+
+ + + +
+
{{ t("common.loading") }}
-
+
{{ t("settings.jdbcNoDrivers") }}
{{ t("driverStore.noMatchingDrivers") }}
-
+
-
{{ driver.name }}
-
{{ driver.path }}
+
+
{{ item.title }}
+ + {{ item.source }} + +
+
{{ item.subtitle }}
-
{{ formatBytes(driver.size) }}
-
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue index 9d5feafb17..ada4bc48ee 100644 --- a/apps/desktop/src/components/connection/ConnectionDialog.vue +++ b/apps/desktop/src/components/connection/ConnectionDialog.vue @@ -10,7 +10,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@ 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 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 +33,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,6 +251,7 @@ const customDriverName = ref(""); const mongoUseUrl = ref(false); const jdbcDriverPathsInput = ref(""); const jdbcDrivers = ref([]); +const jdbcMavenBundles = ref([]); const agentDrivers = ref([]); const selectedJdbcDriverPath = ref(""); const connectionUrlInput = ref(""); @@ -270,6 +276,24 @@ const isPresetColor = (color: string | undefined) => colorOptions.some((c) => c. const customColorInput = ref(""); const customColorOpen = ref(false); +const jdbcDriverSelectItems = computed(() => { + 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]))); + function applyCustomColor(value: string) { form.value.color = value; customColorInput.value = value; @@ -1939,9 +1963,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 +1989,20 @@ 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); } function openExternalUrl(url: string) { @@ -2207,13 +2236,13 @@ function openExternalUrl(url: string) {
- - - {{ driver.name }} + + {{ driver.label }} diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index 7861564799..f344cf2cea 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -2076,6 +2076,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", @@ -2088,6 +2090,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}", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index b563f69928..529f74cdfb 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -2075,6 +2075,8 @@ progressJreExtract: "解压 JRE...", progressDownloadJre: "下载 JRE", progressDownloadDriver: "下载驱动", + progressDownloadJdbcPlugin: "下载 JDBC 插件", + progressJdbcPluginExtract: "安装 JDBC 插件...", usageTitle: "空间占用明细", usageTotal: "总计 {size}", usageTotalLabel: "总计", @@ -2087,6 +2089,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}", diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts index 7448bd985c..f54ca034d7 100644 --- a/apps/desktop/src/lib/api.ts +++ b/apps/desktop/src/lib/api.ts @@ -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"); diff --git a/apps/desktop/src/lib/http.ts b/apps/desktop/src/lib/http.ts index d13fdc76bb..f272adc4e8 100644 --- a/apps/desktop/src/lib/http.ts +++ b/apps/desktop/src/lib/http.ts @@ -14,6 +14,7 @@ import type { DatabaseType, InstalledPlugin, JdbcDriverInfo, + JdbcMavenBundleInfo, JdbcPluginStatus, SidebarLayout, SavedSqlFile, @@ -176,6 +177,10 @@ export async function listJdbcDrivers(): Promise { return get("/api/jdbc/drivers"); } +export async function listJdbcMavenBundles(): Promise { + return get("/api/jdbc/drivers/maven"); +} + export async function importJdbcDrivers(pathsOrFiles: (string | File)[]): Promise { 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 { + return post("/api/jdbc/drivers/maven", { coordinate, repositories }); +} + export async function deleteJdbcDriver(path: string): Promise { const fileName = path.split("/").pop() || path; return del(`/api/jdbc/drivers/${encodeURIComponent(fileName)}`); } +export async function deleteJdbcMavenBundle(bundleId: string): Promise { + return del(`/api/jdbc/drivers/maven/${encodeURIComponent(bundleId)}`); +} + export async function jdbcPluginStatus(): Promise { return get("/api/jdbc/plugin/status"); } diff --git a/apps/desktop/src/lib/tauri.ts b/apps/desktop/src/lib/tauri.ts index 0ea8ceb32b..308fe58e0e 100644 --- a/apps/desktop/src/lib/tauri.ts +++ b/apps/desktop/src/lib/tauri.ts @@ -16,6 +16,7 @@ import type { DatabaseType, InstalledPlugin, JdbcDriverInfo, + JdbcMavenBundleInfo, JdbcPluginStatus, SavedSqlFile, SavedSqlFolder, @@ -757,6 +758,10 @@ export async function listJdbcDrivers(): Promise { return invoke("list_jdbc_drivers"); } +export async function listJdbcMavenBundles(): Promise { + return invoke("list_jdbc_maven_bundles"); +} + export async function importJdbcDrivers(paths: (string | File)[]): Promise { if (paths.some((path) => typeof path !== "string")) { throw new Error("Desktop JDBC driver import requires local file paths"); @@ -764,10 +769,18 @@ export async function importJdbcDrivers(paths: (string | File)[]): Promise { + return invoke("install_jdbc_driver_from_maven", { request: { coordinate, repositories } }); +} + export async function deleteJdbcDriver(path: string): Promise { return invoke("delete_jdbc_driver", { path }); } +export async function deleteJdbcMavenBundle(bundleId: string): Promise { + return invoke("delete_jdbc_maven_bundle", { bundleId }); +} + export async function jdbcPluginStatus(): Promise { return invoke("jdbc_plugin_status"); } diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts index c83dfe5c8c..99ed74586a 100644 --- a/apps/desktop/src/types/database.ts +++ b/apps/desktop/src/types/database.ts @@ -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 { diff --git a/crates/dbx-core/src/jdbc.rs b/crates/dbx-core/src/jdbc.rs index c01021d2cd..ab2836f95c 100644 --- a/crates/dbx-core/src/jdbc.rs +++ b/crates/dbx-core/src/jdbc.rs @@ -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, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct JdbcMavenInstallRequest { + pub coordinate: String, + #[serde(default)] + pub repositories: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct JdbcMavenBundleInfo { + pub id: String, + pub coordinate: String, + pub scope: String, + pub repositories: Vec, + pub installed_at: String, + pub path: String, + pub artifacts: Vec, +} + +#[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, Str list_jdbc_drivers_from_dir(&jdbc_drivers_dir(plugins_root)) } +pub fn list_jdbc_maven_bundles(plugins_root: &Path) -> Result, String> { + list_jdbc_maven_bundles_from_dir(&jdbc_maven_drivers_dir(plugins_root)) +} + pub fn import_jdbc_drivers(plugins_root: &Path, paths: &[String]) -> Result, 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 Result, 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, 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 { @@ -77,13 +173,23 @@ pub async fn get_jdbc_plugin_status(plugins_root: &Path) -> Result Result { - 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 { + 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 { @@ -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 { 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 { fetch_latest_release().await.ok().and_then(|release| release.jdbc_plugin) } -async fn download_jdbc_plugin_zip() -> Result, String> { +async fn download_jdbc_plugin_zip_with_progress(progress: &impl Fn(AgentProgressEvent)) -> Result, 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, 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, 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, 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, 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::(&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 { + 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, + artifacts: Vec, +} + +#[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")); + } +} diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs index 2cf90d7a75..47cc0718cb 100644 --- a/crates/dbx-web/src/main.rs +++ b/crates/dbx-web/src/main.rs @@ -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)) diff --git a/crates/dbx-web/src/routes/jdbc.rs b/crates/dbx-web/src/routes/jdbc.rs index 13977791e8..4a670a53d4 100644 --- a/crates/dbx-web/src/routes/jdbc.rs +++ b/crates/dbx-web/src/routes/jdbc.rs @@ -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>) -> Result>, +) -> Result>, 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>, + Json(req): Json, +) -> Result>, 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>, 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>, + Path(bundle_id): Path, +) -> Result>, 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>) -> Result, AppError> { @@ -59,7 +84,12 @@ pub async fn get_jdbc_plugin_status(State(state): State>) -> Resul pub async fn install_jdbc_plugin(State(state): State>) -> Result, 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>) -> Result pub async fn list_system_fonts() -> Result>, AppError> { Ok(Json(jdbc::list_system_fonts())) } + +async fn progress_sender(state: &WebState, operation_id: &str) -> broadcast::Sender { + let mut channels = state.sse_channels.write().await; + channels + .entry(format!("agent-install-progress:{operation_id}")) + .or_insert_with(|| { + let (tx, _) = broadcast::channel::(256); + tx + }) + .clone() +} + +fn send_progress_event(tx: &broadcast::Sender, event: AgentProgressEvent) { + if let Ok(payload) = serde_json::to_string(&event) { + let _ = tx.send(payload); + } +} diff --git a/plugins/jdbc/bin/dbx-maven-resolver b/plugins/jdbc/bin/dbx-maven-resolver new file mode 100644 index 0000000000..f97f70bef3 --- /dev/null +++ b/plugins/jdbc/bin/dbx-maven-resolver @@ -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 "$@" diff --git a/plugins/jdbc/bin/dbx-maven-resolver.bat b/plugins/jdbc/bin/dbx-maven-resolver.bat new file mode 100644 index 0000000000..f2abd7da05 --- /dev/null +++ b/plugins/jdbc/bin/dbx-maven-resolver.bat @@ -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 %* diff --git a/plugins/jdbc/package.sh b/plugins/jdbc/package.sh index 200c8f24f2..236ba3627d 100755 --- a/plugins/jdbc/package.sh +++ b/plugins/jdbc/package.sh @@ -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" diff --git a/plugins/jdbc/pom.xml b/plugins/jdbc/pom.xml index cfdb51eda0..a563347067 100644 --- a/plugins/jdbc/pom.xml +++ b/plugins/jdbc/pom.xml @@ -10,6 +10,8 @@ 17 17 UTF-8 + 2.0.18 + 4.0.0-rc-5 @@ -33,6 +35,56 @@ commons-lang3 3.18.0 + + org.apache.maven.resolver + maven-resolver-api + ${maven.resolver.version} + + + org.apache.maven.resolver + maven-resolver-spi + ${maven.resolver.version} + + + org.apache.maven.resolver + maven-resolver-util + ${maven.resolver.version} + + + org.apache.maven.resolver + maven-resolver-impl + ${maven.resolver.version} + + + org.apache.maven.resolver + maven-resolver-connector-basic + ${maven.resolver.version} + + + org.apache.maven.resolver + maven-resolver-transport-file + ${maven.resolver.version} + + + org.apache.maven.resolver + maven-resolver-transport-jdk + ${maven.resolver.version} + + + org.apache.maven.resolver + maven-resolver-supplier-mvn4 + ${maven.resolver.version} + + + org.apache.maven + maven-resolver-provider + ${maven.core.version} + + + org.apache.maven + maven-model-builder + ${maven.core.version} + com.h2database h2 diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/maven/DbxMavenResolver.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/maven/DbxMavenResolver.java new file mode 100644 index 0000000000..7f041dd5f3 --- /dev/null +++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/maven/DbxMavenResolver.java @@ -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 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 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 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 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 repositories, + List 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) + ); + } + } +} diff --git a/src-tauri/src/commands/plugins.rs b/src-tauri/src/commands/plugins.rs index 6488acd77d..c779339445 100644 --- a/src-tauri/src/commands/plugins.rs +++ b/src-tauri/src/commands/plugins.rs @@ -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>) -> Result>) -> Result { - jdbc::install_jdbc_plugin(state.plugins.root_dir()).await +pub async fn install_jdbc_plugin( + app: tauri::AppHandle, + state: State<'_, Arc>, +) -> Result { + 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>) -> Result>) -> Result, 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>, + request: JdbcMavenInstallRequest, +) -> Result, String> { + jdbc::install_jdbc_driver_from_maven(state.plugins.root_dir(), request).await +} + #[tauri::command] pub async fn import_jdbc_drivers( state: State<'_, Arc>, @@ -66,3 +90,18 @@ pub async fn delete_jdbc_driver(state: State<'_, Arc>, path: String) - .await .map_err(|err| err.to_string())? } + +#[tauri::command] +pub async fn delete_jdbc_maven_bundle( + state: State<'_, Arc>, + bundle_id: String, +) -> Result, 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); +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 06594792ea..6b83075111 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -348,8 +348,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,