Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(connection): add keepalive interval

t8y2000c2366199f
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index a3e543c911..732a716bf8 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -112,6 +112,7 @@ const defaultForm = (): ConnectionForm => ({
connect_timeout_secs: 5,
query_timeout_secs: 30,
idle_timeout_secs: 60,
+ keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: "",
client_cert_path: "",
@@ -249,6 +250,17 @@ function sshLayersForConfig(config: LegacyConnectionConfig): SshTunnelConfig[] {
}
const form = ref(defaultForm());
+const keepaliveEnabled = computed({
+ get: () => Number(form.value.keepalive_interval_secs) > 0,
+ set: (enabled: boolean) => {
+ if (enabled) {
+ const current = Number(form.value.keepalive_interval_secs);
+ form.value.keepalive_interval_secs = Number.isFinite(current) && current > 0 ? current : 30;
+ } else {
+ form.value.keepalive_interval_secs = 0;
+ }
+ },
+});
const selectedTransportLayerId = ref<string | null>(null);
const draggedTransportLayerId = ref<string | null>(null);
const selectedType = ref("mysql");
@@ -579,6 +591,7 @@ watch(
connect_timeout_secs: config.connect_timeout_secs || 5,
query_timeout_secs: config.query_timeout_secs ?? 30,
idle_timeout_secs: config.idle_timeout_secs ?? 60,
+ keepalive_interval_secs: config.keepalive_interval_secs ?? 0,
ssl: config.ssl || false,
ca_cert_path: config.ca_cert_path || "",
client_cert_path: config.client_cert_path || "",
@@ -1101,6 +1114,8 @@ function connectionConfigForSubmit(id: string): ConnectionConfig {
config.query_timeout_secs = Number.isFinite(queryTimeout) && queryTimeout >= 0 ? queryTimeout : 30;
const idleTimeout = Number(config.idle_timeout_secs);
config.idle_timeout_secs = Number.isFinite(idleTimeout) && idleTimeout >= 0 ? idleTimeout : 60;
+ const keepaliveInterval = Number(config.keepalive_interval_secs);
+ config.keepalive_interval_secs = Number.isFinite(keepaliveInterval) && keepaliveInterval >= 0 ? keepaliveInterval : 0;
if (config.db_type === "manticoresearch") {
config.url_params = "";
}
@@ -2977,6 +2992,13 @@ function openExternalUrl(url: string) {
<Label class="text-right text-xs">{{ t("connection.idleTimeout") }}</Label>
<Input v-model.number="form.idle_timeout_secs" type="number" min="0" max="600" step="1" class="col-span-3" />
</div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label class="text-right text-xs">{{ t("connection.keepaliveInterval") }}</Label>
+ <div class="col-span-3 flex items-center gap-2">
+ <Switch v-model="keepaliveEnabled" />
+ <Input v-model.number="form.keepalive_interval_secs" type="number" min="1" max="3600" step="1" class="flex-1" :disabled="!keepaliveEnabled" />
+ </div>
+ </div>
<div class="grid grid-cols-4 items-center gap-4">
<Label class="text-right text-xs">{{ t("connection.readOnly") }}</Label>
<label class="col-span-3 flex items-center gap-2 cursor-pointer">
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 9c234a6bbd..463d691f8c 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -305,6 +305,7 @@
connectTimeout: "Connection Timeout (seconds)",
queryTimeout: "Query Timeout (seconds)",
idleTimeout: "Idle Timeout (seconds)",
+ keepaliveInterval: "Keepalive Interval (seconds)",
readOnly: "Read Only",
readOnlyHint: "Block all write operations (INSERT, UPDATE, DELETE, etc.)",
readOnlyBadge: "Read-only",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index b55b1eff48..081c625f83 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -286,6 +286,7 @@
connectTimeout: "Tiempo de espera de conexión (segundos)",
queryTimeout: "Tiempo de espera de consulta (segundos)",
idleTimeout: "Tiempo de espera inactivo (segundos)",
+ keepaliveInterval: "Intervalo de keepalive (segundos)",
readOnly: "Solo lectura",
readOnlyHint: "Bloquear todas las operaciones de escritura (INSERT, UPDATE, DELETE, etc.)",
readOnlyBadge: "Solo lectura",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 18a06017e6..7c75b25482 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -291,6 +291,7 @@
connectTimeout: "Timeout Connessione (secondi)",
queryTimeout: "Timeout Query (secondi)",
idleTimeout: "Timeout Inattività (secondi)",
+ keepaliveInterval: "Intervallo keepalive (secondi)",
readOnly: "Sola lettura",
readOnlyHint: "Blocca tutte le operazioni di scrittura (INSERT, UPDATE, DELETE, ecc.)",
readOnlyBadge: "Sola lettura",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 5fec0ba3fc..73bcc6cf78 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -304,6 +304,7 @@ export default {
connectTimeout: "接続タイムアウト(秒)",
queryTimeout: "クエリタイムアウト(秒)",
idleTimeout: "アイドルタイムアウト(秒)",
+ keepaliveInterval: "Keepalive 間隔(秒)",
readOnly: "読み取り専用",
readOnlyHint: "すべての書き込み操作(INSERT, UPDATE, DELETEなど)をブロックします",
readOnlyBadge: "読み取り専用",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 2e6944417b..824a81981d 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -291,6 +291,7 @@
connectTimeout: "Timeout de Conexão (segundos)",
queryTimeout: "Timeout de Consulta (segundos)",
idleTimeout: "Timeout de Inatividade (segundos)",
+ keepaliveInterval: "Intervalo de keepalive (segundos)",
readOnly: "Somente leitura",
readOnlyHint: "Bloquear todas as operações de escrita (INSERT, UPDATE, DELETE, etc.)",
readOnlyBadge: "Somente leitura",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index ae0161a843..f3aa9c8f7a 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -306,6 +306,7 @@
connectTimeout: "连接超时(秒)",
queryTimeout: "查询超时(秒)",
idleTimeout: "空闲超时(秒)",
+ keepaliveInterval: "保持连接间隔(秒)",
readOnly: "只读模式",
readOnlyHint: "阻止所有写操作(INSERT、UPDATE、DELETE 等)",
readOnlyBadge: "只读",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 0749309dec..6b23987b52 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -291,6 +291,7 @@
connectTimeout: "連線逾時(秒)",
queryTimeout: "查詢逾時(秒)",
idleTimeout: "閒置逾時(秒)",
+ keepaliveInterval: "保持連線間隔(秒)",
readOnly: "唯讀模式",
readOnlyHint: "阻止所有寫入操作(INSERT、UPDATE、DELETE 等)",
readOnlyBadge: "唯讀",
diff --git a/apps/desktop/src/lib/navicatImport.ts b/apps/desktop/src/lib/navicatImport.ts
index 1beec96ec3..d2659df147 100644
--- a/apps/desktop/src/lib/navicatImport.ts
+++ b/apps/desktop/src/lib/navicatImport.ts
@@ -54,6 +54,11 @@ function getAny(values: Record<string, string>, keys: string[]) {
return "";
}
+function truthyNavicatFlag(value: string) {
+ const normalized = value.trim().toLowerCase();
+ return ["1", "true", "yes", "y", "on", "checked"].includes(normalized);
+}
+
function hexToBytes(hex: string) {
const clean = hex.trim();
if (!clean || clean.length % 2 !== 0 || /[^0-9a-f]/i.test(clean)) return null;
@@ -161,6 +166,10 @@ async function parseConnection(node: ParsedNode): Promise<ConnectionConfig | nul
const oracleConnectionType = profile.dbType === "oracle" && getAny(node.values, ["sid"]) ? "sid" : profile.dbType === "oracle" ? "service_name" : undefined;
const username = getAny(node.values, ["user", "username", "userName", "uid"]) || profile.user;
const password = await decryptNavicatPassword(getAny(node.values, ["password"]));
+ const keepaliveValue = Number(getAny(node.values, ["keepAliveInterval", "keepaliveInterval", "keepAliveTime", "keepaliveTime"]));
+ const keepaliveFlag = getAny(node.values, ["keepAlive", "keepalive", "useKeepAlive", "enableKeepAlive"]);
+ const keepaliveEnabled = !keepaliveFlag || truthyNavicatFlag(keepaliveFlag);
+ const keepaliveInterval = Number.isFinite(keepaliveValue) && keepaliveValue > 0 && keepaliveEnabled ? keepaliveValue : 0;
const config: PartialConnection = {
name,
@@ -177,6 +186,7 @@ async function parseConnection(node: ParsedNode): Promise<ConnectionConfig | nul
transport_layers: [],
connect_timeout_secs: 5,
query_timeout_secs: 30,
+ keepalive_interval_secs: keepaliveInterval,
ssl: false,
oracle_connection_type: oracleConnectionType,
connection_string: undefined,
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 56e6a2bcdc..33e4b5d5f8 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -305,6 +305,7 @@ export const useConnectionStore = defineStore("connection", () => {
connect_timeout_secs: config.connect_timeout_secs || 5,
query_timeout_secs: config.query_timeout_secs ?? 30,
idle_timeout_secs: config.idle_timeout_secs ?? 60,
+ keepalive_interval_secs: config.keepalive_interval_secs ?? 0,
};
}
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 30fe36d719..43fba67443 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -80,6 +80,7 @@ export interface ConnectionConfig {
connect_timeout_secs?: number;
query_timeout_secs?: number;
idle_timeout_secs?: number;
+ keepalive_interval_secs?: number;
ssl?: boolean;
ca_cert_path?: string;
client_cert_path?: string;
diff --git a/crates/dbx-core/src/agent_connection.rs b/crates/dbx-core/src/agent_connection.rs
index 7b88f0a94d..57fd560003 100644
--- a/crates/dbx-core/src/agent_connection.rs
+++ b/crates/dbx-core/src/agent_connection.rs
@@ -522,8 +522,8 @@ fn append_agent_url_params(base: String, params: Option<&str>) -> String {
mod tests {
use super::*;
use crate::models::connection::{
- default_connect_timeout_secs, default_idle_timeout_secs, default_query_timeout_secs,
- default_redis_key_separator,
+ default_connect_timeout_secs, default_idle_timeout_secs, default_keepalive_interval_secs,
+ default_query_timeout_secs, default_redis_key_separator,
};
fn config(db_type: DatabaseType, database: Option<&str>) -> ConnectionConfig {
@@ -546,6 +546,7 @@ mod tests {
connect_timeout_secs: default_connect_timeout_secs(),
query_timeout_secs: default_query_timeout_secs(),
idle_timeout_secs: default_idle_timeout_secs(),
+ keepalive_interval_secs: default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/crates/dbx-core/src/cloud_sync.rs b/crates/dbx-core/src/cloud_sync.rs
index 8d6e70cf67..19f1679ef4 100644
--- a/crates/dbx-core/src/cloud_sync.rs
+++ b/crates/dbx-core/src/cloud_sync.rs
@@ -580,6 +580,7 @@ mod tests {
connect_timeout_secs: 5,
query_timeout_secs: 30,
idle_timeout_secs: 60,
+ keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rs
index 6500e55931..3a4deeb8c5 100644
--- a/crates/dbx-core/src/connection.rs
+++ b/crates/dbx-core/src/connection.rs
@@ -1,7 +1,9 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
+use std::time::Duration;
use tokio::sync::RwLock;
+use tokio::task::JoinHandle;
use mysql_async::prelude::Queryable;
use mysql_async::Row as MysqlRow;
@@ -72,6 +74,7 @@ pub enum PoolKind {
pub struct AppState {
pub connections: RwLock<HashMap<String, PoolKind>>,
+ keepalive_tasks: RwLock<HashMap<String, JoinHandle<()>>>,
pub configs: RwLock<HashMap<String, ConnectionConfig>>,
pub running_queries: RunningQueries,
pub tunnels: TunnelManager,
@@ -248,6 +251,7 @@ impl AppState {
) -> Self {
Self {
connections: RwLock::new(HashMap::new()),
+ keepalive_tasks: RwLock::new(HashMap::new()),
configs: RwLock::new(HashMap::new()),
running_queries: RunningQueries::default(),
tunnels: TunnelManager::new(),
@@ -307,6 +311,63 @@ impl AppState {
Ok(PluginRuntimeEnv::default().with_var("DBX_JAVA_BIN", java.to_string_lossy().to_string()))
}
+ pub async fn insert_connection_pool(&self, pool_key: String, pool: PoolKind, config: &ConnectionConfig) {
+ self.stop_keepalive_task(&pool_key).await;
+ self.start_keepalive_task(&pool_key, &pool, config).await;
+ let previous = self.connections.write().await.insert(pool_key, pool);
+ if let Some(pool) = previous {
+ close_pool_kind(pool).await;
+ }
+ }
+
+ async fn start_keepalive_task(&self, pool_key: &str, pool: &PoolKind, config: &ConnectionConfig) {
+ let interval_secs = config.keepalive_interval_secs;
+ if interval_secs == 0 {
+ return;
+ }
+ let Some(mut target) = keepalive_target_from_pool(pool, config) else {
+ log::debug!(
+ "Connection keepalive requested for '{pool_key}', but this database driver does not keep a pingable client handle."
+ );
+ return;
+ };
+
+ let key = pool_key.to_string();
+ let interval = Duration::from_secs(interval_secs.max(1));
+ let timeout = Duration::from_secs(config.effective_connect_timeout_secs().max(1));
+ let handle = tokio::spawn(async move {
+ loop {
+ tokio::time::sleep(interval).await;
+ let result = tokio::time::timeout(timeout, ping_keepalive_target(&mut target, timeout)).await;
+ match result {
+ Ok(Ok(())) => {}
+ Ok(Err(err)) => log::warn!("Connection keepalive failed for '{key}': {err}"),
+ Err(_) => log::warn!("Connection keepalive timed out for '{key}' after {}s", timeout.as_secs()),
+ }
+ }
+ });
+ let previous = self.keepalive_tasks.write().await.insert(pool_key.to_string(), handle);
+ if let Some(previous) = previous {
+ previous.abort();
+ }
+ }
+
+ async fn stop_keepalive_task(&self, pool_key: &str) {
+ let task = self.keepalive_tasks.write().await.remove(pool_key);
+ if let Some(task) = task {
+ task.abort();
+ }
+ }
+
+ async fn stop_keepalive_tasks(&self, pool_keys: &[String]) {
+ let mut tasks = self.keepalive_tasks.write().await;
+ for pool_key in pool_keys {
+ if let Some(task) = tasks.remove(pool_key) {
+ task.abort();
+ }
+ }
+ }
+
pub async fn get_or_create_pool(&self, connection_id: &str, database: Option<&str>) -> Result<String, String> {
self.get_or_create_pool_for_session(connection_id, database, None).await
}
@@ -456,12 +517,12 @@ impl AppState {
.await
{
Ok(()) => {
- let mut conns = self.connections.write().await;
// Re-check: another task may have created the pool while we were connecting.
- if conns.contains_key(&pool_key) {
+ if self.connections.read().await.contains_key(&pool_key) {
return Ok(pool_key);
}
- conns.insert(pool_key.clone(), PoolKind::MongoDb(client));
+ self.insert_connection_pool(pool_key.clone(), PoolKind::MongoDb(client), &db_config)
+ .await;
return Ok(pool_key);
}
Err(e) => e,
@@ -679,7 +740,7 @@ impl AppState {
}
};
- self.connections.write().await.insert(pool_key.clone(), pool);
+ self.insert_connection_pool(pool_key.clone(), pool, &db_config).await;
Ok(pool_key)
}
@@ -741,6 +802,7 @@ impl AppState {
return false;
}
+ self.stop_keepalive_task(pool_key).await;
let removed = self.connections.write().await.remove(pool_key);
if let Some(pool) = removed {
close_pool_kind(pool).await;
@@ -770,6 +832,7 @@ impl AppState {
self.remove_connection_pools(connection_id).await;
self.reset_connection_transport(connection_id).await;
} else {
+ self.stop_keepalive_task(&pool_key).await;
let removed = self.connections.write().await.remove(&pool_key);
if let Some(pool) = removed {
close_pool_kind(pool).await;
@@ -797,6 +860,7 @@ impl AppState {
if pool_key == base_pool_key {
return Ok(false);
}
+ self.stop_keepalive_task(&pool_key).await;
let removed = self.connections.write().await.remove(&pool_key);
if let Some(pool) = removed {
close_pool_kind(pool).await;
@@ -816,9 +880,16 @@ impl AppState {
}
let base_pool_key = base_pool_key_for(db_type, connection_id, database, false);
let session_prefix = format!("{base_pool_key}:session:");
+ let keys_to_remove: Vec<String> = self
+ .connections
+ .read()
+ .await
+ .keys()
+ .filter(|key| *key == &base_pool_key || key.starts_with(&session_prefix))
+ .cloned()
+ .collect();
+ self.stop_keepalive_tasks(&keys_to_remove).await;
let mut conns = self.connections.write().await;
- let keys_to_remove: Vec<String> =
- conns.keys().filter(|key| *key == &base_pool_key || key.starts_with(&session_prefix)).cloned().collect();
let mut removed = Vec::with_capacity(keys_to_remove.len());
for key in keys_to_remove {
if let Some(pool) = conns.remove(&key) {
@@ -969,6 +1040,7 @@ impl AppState {
// Remove dead pools
if !dead_keys.is_empty() {
+ self.stop_keepalive_tasks(&dead_keys).await;
let mut conns = self.connections.write().await;
for key in &dead_keys {
if let Some(pool) = conns.remove(key) {
@@ -989,12 +1061,17 @@ impl AppState {
}
pub async fn remove_connection_pools(&self, connection_id: &str) {
- let mut conns = self.connections.write().await;
- let keys_to_remove: Vec<String> = conns
+ let pool_prefix = format!("{connection_id}:");
+ let keys_to_remove: Vec<String> = self
+ .connections
+ .read()
+ .await
.keys()
- .filter(|k| *k == connection_id || k.starts_with(&format!("{connection_id}:")))
+ .filter(|k| *k == connection_id || k.starts_with(&pool_prefix))
.cloned()
.collect();
+ self.stop_keepalive_tasks(&keys_to_remove).await;
+ let mut conns = self.connections.write().await;
let mut removed = Vec::with_capacity(keys_to_remove.len());
for key in keys_to_remove {
if let Some(pool) = conns.remove(&key) {
@@ -1013,6 +1090,61 @@ impl AppState {
}
}
+enum KeepaliveTarget {
+ Mysql(db::mysql::MySqlPool),
+ Postgres(deadpool_postgres::Pool),
+ Rqlite(db::rqlite_driver::RqliteClient),
+ Turso(db::turso_driver::TursoClient),
+ MongoDb { client: mongodb::Client, database: Option<String> },
+ ClickHouse(db::clickhouse_driver::ChClient),
+ SqlServer(Arc<tokio::sync::Mutex<db::sqlserver::SqlServerClient>>),
+ Elasticsearch(db::elasticsearch_driver::EsClient),
+ InfluxDb(db::influxdb_driver::InfluxdbClient),
+}
+
+fn keepalive_target_from_pool(pool: &PoolKind, config: &ConnectionConfig) -> Option<KeepaliveTarget> {
+ match pool {
+ PoolKind::Mysql(pool, _) => Some(KeepaliveTarget::Mysql(pool.clone())),
+ PoolKind::Postgres(pool) => Some(KeepaliveTarget::Postgres(pool.clone())),
+ PoolKind::Rqlite(client) => Some(KeepaliveTarget::Rqlite(client.clone())),
+ PoolKind::Turso(client) => Some(KeepaliveTarget::Turso(client.clone())),
+ PoolKind::MongoDb(client) => Some(KeepaliveTarget::MongoDb {
+ client: client.clone(),
+ database: config.effective_database().map(str::to_string),
+ }),
+ PoolKind::ClickHouse(client) => Some(KeepaliveTarget::ClickHouse(client.clone())),
+ PoolKind::SqlServer(client) => Some(KeepaliveTarget::SqlServer(client.clone())),
+ PoolKind::Elasticsearch(client) => Some(KeepaliveTarget::Elasticsearch(client.clone())),
+ PoolKind::InfluxDb(client) => Some(KeepaliveTarget::InfluxDb(client.clone())),
+ _ => None,
+ }
+}
+
+async fn ping_keepalive_target(target: &mut KeepaliveTarget, timeout: Duration) -> Result<(), String> {
+ match target {
+ KeepaliveTarget::Mysql(pool) => {
+ let mut conn = db::mysql::get_conn_with_health_check(pool).await?;
+ conn.ping().await.map_err(|e| e.to_string())
+ }
+ KeepaliveTarget::Postgres(pool) => {
+ let client = pool.get().await.map_err(|e| format!("PostgreSQL pool error: {e}"))?;
+ client.simple_query("SELECT 1").await.map(|_| ()).map_err(|e| e.to_string())
+ }
+ KeepaliveTarget::Rqlite(client) => db::rqlite_driver::test_connection(client, timeout).await,
+ KeepaliveTarget::Turso(client) => db::turso_driver::test_connection(client, timeout).await,
+ KeepaliveTarget::MongoDb { client, database } => {
+ db::mongo_driver::test_connection(client, timeout, database.as_deref()).await
+ }
+ KeepaliveTarget::ClickHouse(client) => db::clickhouse_driver::test_connection(client, timeout).await,
+ KeepaliveTarget::SqlServer(client) => {
+ let mut client = client.lock().await;
+ db::sqlserver::test_connection(&mut client).await
+ }
+ KeepaliveTarget::Elasticsearch(client) => db::elasticsearch_driver::test_connection(client, timeout).await,
+ KeepaliveTarget::InfluxDb(client) => db::influxdb_driver::test_connection(client, timeout).await,
+ }
+}
+
fn connection_remote_endpoint(config: &ConnectionConfig) -> (String, u16) {
if config.db_type == DatabaseType::MongoDb {
config
@@ -1373,6 +1505,7 @@ mod tests {
connect_timeout_secs: default_connect_timeout_secs(),
query_timeout_secs: crate::models::connection::default_query_timeout_secs(),
idle_timeout_secs: crate::models::connection::default_idle_timeout_secs(),
+ keepalive_interval_secs: crate::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/crates/dbx-core/src/connection_secrets.rs b/crates/dbx-core/src/connection_secrets.rs
index b005e84ede..8fa5af1911 100644
--- a/crates/dbx-core/src/connection_secrets.rs
+++ b/crates/dbx-core/src/connection_secrets.rs
@@ -492,6 +492,7 @@ mod tests {
connect_timeout_secs: crate::models::connection::default_connect_timeout_secs(),
query_timeout_secs: crate::models::connection::default_query_timeout_secs(),
idle_timeout_secs: crate::models::connection::default_idle_timeout_secs(),
+ keepalive_interval_secs: crate::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/crates/dbx-core/src/db/redis_driver.rs b/crates/dbx-core/src/db/redis_driver.rs
index 4e749b8719..fa9496e5e8 100644
--- a/crates/dbx-core/src/db/redis_driver.rs
+++ b/crates/dbx-core/src/db/redis_driver.rs
@@ -2068,6 +2068,7 @@ mod tests {
connect_timeout_secs: crate::models::connection::default_connect_timeout_secs(),
query_timeout_secs: crate::models::connection::default_query_timeout_secs(),
idle_timeout_secs: crate::models::connection::default_idle_timeout_secs(),
+ keepalive_interval_secs: crate::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/crates/dbx-core/src/models/connection.rs b/crates/dbx-core/src/models/connection.rs
index 723bdf837e..d692c34fbc 100644
--- a/crates/dbx-core/src/models/connection.rs
+++ b/crates/dbx-core/src/models/connection.rs
@@ -32,6 +32,8 @@ pub struct ConnectionConfig {
pub query_timeout_secs: u64,
#[serde(default = "default_idle_timeout_secs")]
pub idle_timeout_secs: u64,
+ #[serde(default = "default_keepalive_interval_secs")]
+ pub keepalive_interval_secs: u64,
#[serde(default)]
pub ssl: bool,
#[serde(default, skip_serializing_if = "String::is_empty")]
@@ -194,6 +196,10 @@ pub fn default_idle_timeout_secs() -> u64 {
60
}
+pub fn default_keepalive_interval_secs() -> u64 {
+ 0
+}
+
fn default_proxy_port() -> u16 {
1080
}
@@ -327,6 +333,8 @@ struct ConnectionConfigData {
pub query_timeout_secs: u64,
#[serde(default = "default_idle_timeout_secs")]
pub idle_timeout_secs: u64,
+ #[serde(default = "default_keepalive_interval_secs")]
+ pub keepalive_interval_secs: u64,
#[serde(default)]
pub ssl: bool,
#[serde(default)]
@@ -394,6 +402,7 @@ impl From<ConnectionConfigData> for ConnectionConfig {
connect_timeout_secs: data.connect_timeout_secs,
query_timeout_secs: data.query_timeout_secs,
idle_timeout_secs: data.idle_timeout_secs,
+ keepalive_interval_secs: data.keepalive_interval_secs,
ssl: data.ssl,
ca_cert_path: data.ca_cert_path,
client_cert_path: data.client_cert_path,
@@ -1413,6 +1422,7 @@ mod tests {
connect_timeout_secs: super::default_connect_timeout_secs(),
query_timeout_secs: default_query_timeout_secs(),
idle_timeout_secs: super::default_idle_timeout_secs(),
+ keepalive_interval_secs: super::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/crates/dbx-core/src/query.rs b/crates/dbx-core/src/query.rs
index dceb3b92a6..53c1f5a713 100644
--- a/crates/dbx-core/src/query.rs
+++ b/crates/dbx-core/src/query.rs
@@ -2153,6 +2153,7 @@ mod tests {
connect_timeout_secs: 5,
query_timeout_secs: 30,
idle_timeout_secs: 60,
+ keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/crates/dbx-core/src/schema.rs b/crates/dbx-core/src/schema.rs
index 85601f903e..d203a3d476 100644
--- a/crates/dbx-core/src/schema.rs
+++ b/crates/dbx-core/src/schema.rs
@@ -646,6 +646,7 @@ mod tests {
connect_timeout_secs: 5,
query_timeout_secs: 30,
idle_timeout_secs: 60,
+ keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/crates/dbx-core/src/schema/normalization.rs b/crates/dbx-core/src/schema/normalization.rs
index c0a9c50251..748d546227 100644
--- a/crates/dbx-core/src/schema/normalization.rs
+++ b/crates/dbx-core/src/schema/normalization.rs
@@ -163,6 +163,7 @@ mod tests {
connect_timeout_secs: 5,
query_timeout_secs: 30,
idle_timeout_secs: 60,
+ keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/crates/dbx-core/src/transfer.rs b/crates/dbx-core/src/transfer.rs
index df836d91d9..400af9a83b 100644
--- a/crates/dbx-core/src/transfer.rs
+++ b/crates/dbx-core/src/transfer.rs
@@ -3328,6 +3328,7 @@ mod tests {
connect_timeout_secs: 5,
query_timeout_secs: 30,
idle_timeout_secs: 60,
+ keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/live_postgres_transfer.rs b/crates/dbx-core/tests/live_postgres_transfer.rs
index a53a8d2a20..c0ce9692c9 100644
--- a/crates/dbx-core/tests/live_postgres_transfer.rs
+++ b/crates/dbx-core/tests/live_postgres_transfer.rs
@@ -28,6 +28,7 @@ fn postgres_test_config(id: &str, database: &str) -> ConnectionConfig {
connect_timeout_secs: 5,
query_timeout_secs: 30,
idle_timeout_secs: 60,
+ keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rs
index ffdeb303c9..0ea572031a 100644
--- a/crates/dbx-web/src/routes/connection.rs
+++ b/crates/dbx-web/src/routes/connection.rs
@@ -49,12 +49,7 @@ pub async fn test_connection(
// Clean up any pool keys created for the temporary connection, including
// database-scoped keys like "__test_uuid:database".
- let mut connections = app.connections.write().await;
- let temp_keys: Vec<String> = connections.keys().filter(|key| key.starts_with(&temp_id)).cloned().collect();
- for key in temp_keys {
- connections.remove(&key);
- }
- drop(connections);
+ app.remove_connection_pools(&temp_id).await;
app.configs.write().await.remove(&temp_id);
match result {
@@ -101,16 +96,8 @@ pub async fn disconnect_db(
Json(body): Json<DisconnectRequest>,
) -> Result<Json<()>, AppError> {
let app = &state.app;
- let mut connections = app.connections.write().await;
-
- let pool_prefix = format!("{}:", body.connection_id);
- let keys_to_remove: Vec<String> =
- connections.keys().filter(|k| *k == &body.connection_id || k.starts_with(&pool_prefix)).cloned().collect();
- for key in keys_to_remove {
- connections.remove(&key);
- }
- drop(connections);
+ app.remove_connection_pools(&body.connection_id).await;
app.reset_connection_transport(&body.connection_id).await;
if body.connection_id.starts_with("__visible_draft_") {
app.configs.write().await.remove(&body.connection_id);
@@ -183,6 +170,7 @@ mod tests {
connect_timeout_secs: dbx_core::models::connection::default_connect_timeout_secs(),
query_timeout_secs: dbx_core::models::connection::default_query_timeout_secs(),
idle_timeout_secs: dbx_core::models::connection::default_idle_timeout_secs(),
+ keepalive_interval_secs: dbx_core::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
diff --git a/packages/node-core/src/connections.ts b/packages/node-core/src/connections.ts
index ffe652f080..08234ac478 100644
--- a/packages/node-core/src/connections.ts
+++ b/packages/node-core/src/connections.ts
@@ -16,6 +16,7 @@ export interface ConnectionConfig {
database?: string;
url_params?: string;
transport_layers?: TransportLayerConfig[];
+ keepalive_interval_secs?: number;
ssl: boolean;
ca_cert_path?: string;
oracle_connection_type?: "service_name" | "sid";
diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs
index fd33e16461..135594fb7e 100644
--- a/src-tauri/src/commands/connection.rs
+++ b/src-tauri/src/commands/connection.rs
@@ -190,6 +190,7 @@ mod tests {
connect_timeout_secs: dbx_core::models::connection::default_connect_timeout_secs(),
query_timeout_secs: dbx_core::models::connection::default_query_timeout_secs(),
idle_timeout_secs: dbx_core::models::connection::default_idle_timeout_secs(),
+ keepalive_interval_secs: dbx_core::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
client_cert_path: String::new(),
@@ -590,7 +591,7 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
{
Ok(()) => {
state.configs.write().await.insert(id.clone(), config);
- state.connections.write().await.insert(id.clone(), PoolKind::MongoDb(client));
+ state.insert_connection_pool(id.clone(), PoolKind::MongoDb(client), &db_config).await;
return Ok(id);
}
Err(e) => e,
@@ -707,7 +708,7 @@ pub async fn connect_db(state: State<'_, Arc<AppState>>, config: ConnectionConfi
db_type => return Err(format!("Unsupported database type: {db_type:?}")),
};
- state.connections.write().await.insert(id.clone(), pool);
+ state.insert_connection_pool(id.clone(), pool, &db_config).await;
state.configs.write().await.insert(id.clone(), config);
Ok(id)
@@ -733,15 +734,7 @@ pub async fn connection_final_proxy_port(
#[tauri::command]
pub async fn disconnect_db(state: State<'_, Arc<AppState>>, connection_id: String) -> Result<(), String> {
- let mut conns = state.connections.write().await;
- let keys_to_remove: Vec<String> =
- conns.keys().filter(|k| *k == &connection_id || k.starts_with(&format!("{connection_id}:"))).cloned().collect();
- for key in keys_to_remove {
- if let Some(pool) = conns.remove(&key) {
- dbx_core::connection::close_pool_kind(pool).await;
- }
- }
- drop(conns);
+ state.remove_connection_pools(&connection_id).await;
state.reset_connection_transport(&connection_id).await;
if connection_id.starts_with("__visible_draft_") {
state.configs.write().await.remove(&connection_id);