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。

fix(kingbase): cache live mode for backend SQL execution (#12825)

Hand Sonic44ac47e2fc3b
diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rs
index 390fb4bd59..3683548e12 100644
--- a/crates/dbx-core/src/connection/mod.rs
+++ b/crates/dbx-core/src/connection/mod.rs
@@ -3385,14 +3385,17 @@ impl AppState {
}
};
if db_config.db_type == DatabaseType::Kingbase {
- let identifier_quote = client
- .connection_info(Some(agent_connect_timeout(&db_config)))
- .await
- .ok()
- .map(|info| info.identifier_quote);
- client.set_identifier_quote(identifier_quote);
+ let info = client.connection_info(Some(agent_connect_timeout(&db_config))).await.ok();
+ client.set_identifier_quote(info.as_ref().map(|info| info.identifier_quote.clone()));
+ // database_mode is fixed for the instance. Cache it on the
+ // live pool, never reuse the saved frontend metadata.
+ let mode = info.and_then(|info| info.compatibility_mode);
+ PoolKind::Agent(Arc::new(
+ db::agent_driver::PooledAgentClient::new(client).with_compatibility_mode(mode),
+ ))
+ } else {
+ PoolKind::agent(client)
}
- PoolKind::agent(client)
} else {
// ZooKeeper JVM properties are connection-scoped; shared agent daemons must not inherit them.
let mut client = self
diff --git a/crates/dbx-core/src/data/sql_file_import.rs b/crates/dbx-core/src/data/sql_file_import.rs
index 228054cc94..505b9639e5 100644
--- a/crates/dbx-core/src/data/sql_file_import.rs
+++ b/crates/dbx-core/src/data/sql_file_import.rs
@@ -59,9 +59,9 @@ pub use failure_log_derive::{
/// the plain PostgreSQL splitter.
#[derive(Debug, Clone, PartialEq, Eq)]
enum SqlCompatibilityMode {
- /// The database type has no compatibility-mode concept (non-openGauss).
+ /// The database type has no runtime SQL compatibility-mode concept.
NotApplicable,
- /// The database is openGauss but the probe failed or the pool was
+ /// The database is openGauss/Kingbase but the probe failed or the pool was
/// unavailable. The parser must not fall back to PostgreSQL semantics;
/// it uses the PL/SQL-capable openGauss profile so an A-mode package body
/// is never split on its inner semicolons.
@@ -74,7 +74,7 @@ impl SqlCompatibilityMode {
/// The mode string for [`SqlParsingOptions::for_database_type_and_compatibility`],
/// or `None` when the database has no mode concept or the mode is unknown.
///
- /// `None` is interpreted as "unknown openGauss" by the parser (see that
+ /// `None` is interpreted as an unknown mode by the applicable parser (see that
/// function), which selects the conservative PL/SQL-capable profile.
fn as_mode_str(&self) -> Option<&str> {
match self {
@@ -2326,7 +2326,17 @@ async fn sql_file_import_target(state: &AppState, connection_id: &str, database:
// still uses the openGauss splitter. A failed probe is recorded as `Unknown`
// rather than `None` so the splitter keeps PL/SQL package bodies intact
// instead of silently falling back to PostgreSQL statement semantics.
- let compatibility_mode = if config.db_type == DatabaseType::OpenGauss {
+ let compatibility_mode = if config.db_type == DatabaseType::Kingbase {
+ match state.get_or_create_pool(connection_id, Some(database)).await {
+ Ok(pool_key) => {
+ match crate::query::connection_sql_compatibility_mode(state, &pool_key, Some(config.db_type)).await {
+ Some(mode) => SqlCompatibilityMode::Resolved(mode),
+ None => SqlCompatibilityMode::Unknown,
+ }
+ }
+ Err(_) => SqlCompatibilityMode::Unknown,
+ }
+ } else if config.db_type == DatabaseType::OpenGauss {
let pool = match state.get_or_create_pool(connection_id, Some(database)).await {
Ok(pool_key) => match state.pool_handle(&pool_key).await {
Some(PoolKind::Postgres(pool)) => Some(pool),
diff --git a/crates/dbx-core/src/query/mod.rs b/crates/dbx-core/src/query/mod.rs
index 786de464fa..4692c5b1fa 100644
--- a/crates/dbx-core/src/query/mod.rs
+++ b/crates/dbx-core/src/query/mod.rs
@@ -883,11 +883,15 @@ fn statement_split_database_type(config: &ConnectionConfig) -> DatabaseType {
}
}
-async fn connection_sql_compatibility_mode(
+pub(crate) async fn connection_sql_compatibility_mode(
state: &AppState,
pool_key: &str,
db_type: Option<DatabaseType>,
) -> Option<String> {
+ if db_type == Some(DatabaseType::Kingbase) {
+ let Some(PoolKind::Agent(client)) = state.pool_handle(pool_key).await else { return None };
+ return client.compatibility_mode().map(str::to_owned);
+ }
if db_type != Some(DatabaseType::OpenGauss) {
return None;
}
@@ -5119,23 +5123,11 @@ pub async fn execute_schema_diff_deploy(
let now = chrono::Utc::now().to_rfc3339();
let db_type = connection_database_type(state, connection_id).await;
- // openGauss A-mode deploy scripts may contain CREATE PACKAGE … / blocks
- // that must stay intact. Probe the database compatibility mode when a pool
- // is available; on failure fall back to the plain openGauss splitter.
- let compatibility_mode = if db_type == Some(DatabaseType::OpenGauss) {
- let pool = match state
- .get_or_create_pool(connection_id, if database.is_empty() { None } else { Some(database) })
- .await
- {
- Ok(pool_key) => match state.pool_handle(&pool_key).await {
- Some(PoolKind::Postgres(pool)) => Some(pool),
- _ => None,
- },
+ // Resolve the live session mode, not the potentially stale saved UI metadata.
+ let compatibility_mode = if matches!(db_type, Some(DatabaseType::OpenGauss | DatabaseType::Kingbase)) {
+ match state.get_or_create_pool(connection_id, if database.is_empty() { None } else { Some(database) }).await {
+ Ok(pool_key) => connection_sql_compatibility_mode(state, &pool_key, db_type).await,
Err(_) => None,
- };
- match pool {
- Some(pool) => db::postgres::opengauss_compatibility_mode(&pool).await.ok().flatten(),
- None => None,
}
} else {
None
diff --git a/crates/dbx-driver-agent/src/agent_driver.rs b/crates/dbx-driver-agent/src/agent_driver.rs
index b2a56f6096..43f1511c46 100644
--- a/crates/dbx-driver-agent/src/agent_driver.rs
+++ b/crates/dbx-driver-agent/src/agent_driver.rs
@@ -885,6 +885,7 @@ pub struct PooledAgentClient {
shared_runtime: Option<Arc<AgentRuntimeClient>>,
agent_session_id: Option<String>,
identifier_quote: Option<String>,
+ compatibility_mode: Option<String>,
}
impl PooledAgentClient {
@@ -892,7 +893,22 @@ impl PooledAgentClient {
let shared_runtime = client.shared_runtime.clone();
let agent_session_id = client.agent_session_id.clone();
let identifier_quote = client.identifier_quote.clone();
- Self { client: tokio::sync::Mutex::new(client), shared_runtime, agent_session_id, identifier_quote }
+ Self {
+ client: tokio::sync::Mutex::new(client),
+ shared_runtime,
+ agent_session_id,
+ identifier_quote,
+ compatibility_mode: None,
+ }
+ }
+
+ pub fn with_compatibility_mode(mut self, mode: Option<String>) -> Self {
+ self.compatibility_mode = mode.filter(|value| !value.trim().is_empty());
+ self
+ }
+
+ pub fn compatibility_mode(&self) -> Option<&str> {
+ self.compatibility_mode.as_deref()
}
pub fn identifier_quote(&self) -> Option<&str> {
@@ -3835,6 +3851,32 @@ mod tests {
use std::time::{Duration, Instant};
use tokio_util::sync::CancellationToken;
+ #[test]
+ fn kingbase_connection_info_and_pool_preserve_reported_mode() {
+ let info: super::AgentConnectionInfo = serde_json::from_value(serde_json::json!({
+ "identifierQuote": "\"", "compatibilityMode": "oracle",
+ "databaseInfo": {"productName": "KingbaseES", "compatibilityMode": "oracle"}
+ }))
+ .unwrap();
+ assert_eq!(info.database_info.unwrap().compatibility_mode.as_deref(), Some("oracle"));
+ let client = AgentDriverClient {
+ child: None,
+ stdin: None,
+ stdout: None,
+ stderr_tail: Arc::new(Mutex::new(StderrTail::default())),
+ handshake: None,
+ next_id: 0,
+ shared_runtime: None,
+ agent_session_id: None,
+ cached_query: None,
+ identifier_quote: None,
+ dedicated_transaction_query_cancel: false,
+ };
+ let pool = super::PooledAgentClient::new(client).with_compatibility_mode(info.compatibility_mode);
+ assert_eq!(pool.compatibility_mode(), Some("oracle"));
+ assert!(pool.with_compatibility_mode(Some(" ".into())).compatibility_mode().is_none());
+ }
+
#[cfg(unix)]
#[test]
fn spawn_repairs_missing_native_execute_permission_after_eacces() {
diff --git a/crates/dbx-sql-core/src/sql.rs b/crates/dbx-sql-core/src/sql.rs
index 6857c558ca..5433b0f8ab 100644
--- a/crates/dbx-sql-core/src/sql.rs
+++ b/crates/dbx-sql-core/src/sql.rs
@@ -445,6 +445,17 @@ impl SqlParsingOptions {
}
pub fn for_database_type_and_compatibility(db_type: DatabaseType, compatibility_mode: Option<&str>) -> Self {
+ if db_type == DatabaseType::Kingbase {
+ let mode = compatibility_mode.unwrap_or_default().trim().to_ascii_lowercase();
+ return Self::from_profile(match mode.as_str() {
+ "mysql" => SqlDialectProfile::mysql_compatible(),
+ "sqlserver" => SqlDialectProfile::sql_server(),
+ "pg" | "postgres" | "postgresql" => SqlDialectProfile::postgres_family(),
+ // Preserve PL/SQL blocks while mode detection is unavailable;
+ // the GaussDB profile also preserves dollar-quoted routines.
+ _ => SqlDialectProfile::gaussdb(),
+ });
+ }
if db_type == DatabaseType::OpenGauss {
return match compatibility_mode.map(str::trim) {
// openGauss stores package specs/bodies as PL/SQL regardless of
@@ -1170,6 +1181,35 @@ pub fn split_sql_statements(sql: &str) -> Vec<String> {
split_sql_statements_with_options(sql, SqlParsingOptions::default())
}
+#[cfg(test)]
+#[test]
+fn kingbase_compatibility_profiles_preserve_routine_and_batch_boundaries() {
+ for (mode, db_type, sql) in [
+ ("oracle", DatabaseType::Gaussdb, "BEGIN\n NULL;\n NULL;\nEND;\n/\nSELECT 1;"),
+ (
+ "mysql",
+ DatabaseType::Mysql,
+ "DELIMITER $$\nCREATE PROCEDURE p() BEGIN SELECT 1; SELECT 2; END$$\nDELIMITER ;\nSELECT 3;",
+ ),
+ (
+ "pg",
+ DatabaseType::Postgres,
+ "CREATE FUNCTION f() RETURNS int AS $$ BEGIN RETURN 1; END; $$ LANGUAGE plpgsql; SELECT 2;",
+ ),
+ (
+ "sqlserver",
+ DatabaseType::SqlServer,
+ "CREATE PROCEDURE p AS\nBEGIN\n SELECT 1;\n SELECT 2;\nEND\nGO\nSELECT 3;",
+ ),
+ ] {
+ assert_eq!(
+ split_sql_statements_for_database_with_compatibility(sql, DatabaseType::Kingbase, Some(mode)),
+ split_sql_statements_for_database(sql, db_type),
+ "Kingbase mode {mode}"
+ );
+ }
+}
+
pub fn split_sql_statements_for_database(sql: &str, db_type: DatabaseType) -> Vec<String> {
sql_execution_plan_for_database(sql, db_type).statements
}