feat(oracle): support oci thick connections via windows agent
This commit is contained in:
1 parent
a1e2d39ed3
commit
8d9e2dc49f
92 files changed
+2551
-143
No files matched your search
@@ -447,6 +447,13 @@
|
||||
"agentKey": "oracle",
|
||||
"label": "Oracle",
|
||||
"storeVisible": false
|
||||
},
|
||||
{
|
||||
"profile": "oci",
|
||||
"agentKey": "oracle-oci",
|
||||
"label": "Oracle (OCI)",
|
||||
"storeVisible": true,
|
||||
"storeOrder": 54
|
||||
}
|
||||
],
|
||||
"singleConnectionPool": true,
|
||||
|
||||
@@ -151,6 +151,8 @@ fn env_required(name: &str) -> Result<String, String> {
|
||||
fn connection_config(id: &str, database: BenchDatabase) -> Result<ConnectionConfig, String> {
|
||||
let database_name = env_required("DBX_BENCH_DATABASE")?;
|
||||
Ok(ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -179,6 +179,8 @@ mod tests {
|
||||
|
||||
fn connection_with_external(value: serde_json::Value) -> ConnectionConfig {
|
||||
let mut cfg = ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "c1".to_string(),
|
||||
name: "mq".to_string(),
|
||||
|
||||
@@ -921,6 +921,8 @@ mod tests {
|
||||
|
||||
fn mq_connection(read_only: bool) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "readonly-mq".to_string(),
|
||||
name: "Read only MQ".to_string(),
|
||||
|
||||
@@ -366,6 +366,8 @@ mod tests {
|
||||
|
||||
fn connection_with_external(value: serde_json::Value) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "nacos-1".to_string(),
|
||||
name: "Nacos".to_string(),
|
||||
|
||||
@@ -642,6 +642,8 @@ mod tests {
|
||||
let storage = crate::persistence::test_storage::open(&dir.join("storage.db")).await.unwrap();
|
||||
let state = AppState::new(storage);
|
||||
let mut cfg = crate::models::connection::ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "nacos-1".to_string(),
|
||||
name: "Nacos".to_string(),
|
||||
@@ -725,6 +727,8 @@ mod tests {
|
||||
let storage = crate::persistence::test_storage::open(&dir.join("storage.db")).await.unwrap();
|
||||
let state = AppState::new(storage);
|
||||
let cfg = crate::models::connection::ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "nacos-rollback".to_string(),
|
||||
name: "Nacos".to_string(),
|
||||
|
||||
@@ -1977,6 +1977,8 @@ for line in sys.stdin:
|
||||
#[cfg(unix)]
|
||||
fn agent_test_connection(id: &str, name: &str, db_type: DatabaseType, database: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
|
||||
@@ -1030,6 +1030,8 @@ mod tests {
|
||||
|
||||
fn connection(id: &str, password: &str, _ssh_password: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: format!("{id} connection"),
|
||||
|
||||
@@ -1361,15 +1361,15 @@ mod tests {
|
||||
assert!(plugins_root.join("jdbc/manifest.json").exists());
|
||||
let bundles = list_jdbc_maven_bundles(&plugins_root).unwrap();
|
||||
assert_eq!(bundles.len(), 1);
|
||||
// 比较 Path 而不是字符串:生产代码在 Windows 上用反斜杠拼接,而被期望值里
|
||||
// 内嵌了 `/`,直接比字符串会在 Windows 上误报。
|
||||
assert_eq!(
|
||||
bundles[0].path,
|
||||
plugins_root.join("jdbc/drivers/maven/com.example_demo-driver_1.0.0").to_string_lossy()
|
||||
std::path::PathBuf::from(&bundles[0].path),
|
||||
plugins_root.join("jdbc/drivers/maven/com.example_demo-driver_1.0.0")
|
||||
);
|
||||
assert_eq!(
|
||||
bundles[0].artifacts[0].path,
|
||||
plugins_root
|
||||
.join("jdbc/drivers/maven/com.example_demo-driver_1.0.0/jars/demo-driver-1.0.0.jar")
|
||||
.to_string_lossy()
|
||||
std::path::PathBuf::from(&bundles[0].artifacts[0].path),
|
||||
plugins_root.join("jdbc/drivers/maven/com.example_demo-driver_1.0.0/jars/demo-driver-1.0.0.jar")
|
||||
);
|
||||
assert_eq!(std::fs::read(&bundles[0].artifacts[0].path).unwrap(), b"offline-driver");
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
|
||||
@@ -1319,6 +1319,25 @@ fn mysql_metadata_fallback_url(
|
||||
Some(connection_url_for_endpoint(config, host, port))
|
||||
}
|
||||
|
||||
/// Global Oracle OCI defaults pulled from editor settings.
|
||||
#[derive(Default)]
|
||||
struct OracleOciDefaults {
|
||||
nls_lang: Option<String>,
|
||||
client_path: Option<String>,
|
||||
tns_admin: Option<String>,
|
||||
}
|
||||
|
||||
/// Trims an optional setting, treating whitespace-only input as unset.
|
||||
fn oracle_oci_trimmed(value: Option<&str>) -> Option<&str> {
|
||||
value.map(str::trim).filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
/// Reads a trimmed non-empty string out of the editor settings blob.
|
||||
fn json_trimmed_string(settings: &serde_json::Value, key: &str) -> Option<String> {
|
||||
let text = settings.get(key)?.as_str()?.trim();
|
||||
(!text.is_empty()).then(|| text.to_string())
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn shared_resource_budget(&self, name: &str, capacity: usize) -> Result<Arc<Semaphore>, String> {
|
||||
if capacity == 0 {
|
||||
@@ -1556,11 +1575,55 @@ impl AppState {
|
||||
error.message
|
||||
}
|
||||
|
||||
/// Resolves the agent-process environment a connection needs.
|
||||
///
|
||||
/// Only Oracle OCI ("thick") connections declare one today. The Oracle
|
||||
/// Client is a process-scoped C library: `NLS_LANG` is read once when the
|
||||
/// client initialises and the Instant Client is located through the platform
|
||||
/// loader path, so neither can travel as a connection parameter — they have
|
||||
/// to be baked into the agent process. Because the environment is part of
|
||||
/// the launch fingerprint, a non-empty result also gives the connection its
|
||||
/// own process instead of sharing one with other Oracle connections.
|
||||
pub async fn agent_launch_env(&self, config: &ConnectionConfig) -> Vec<(String, String)> {
|
||||
if config.driver_profile.as_deref() != Some(crate::oracle_oci::ORACLE_OCI_DRIVER_PROFILE) {
|
||||
return Vec::new();
|
||||
}
|
||||
let defaults = self.oracle_oci_defaults().await;
|
||||
let nls_lang = oracle_oci_trimmed(config.oracle_oci_nls_lang.as_deref())
|
||||
.or_else(|| oracle_oci_trimmed(defaults.nls_lang.as_deref()));
|
||||
// TNS_ADMIN 的解析顺序:连接级字段 > TNS 连接串里打包的目录 > 全局默认。
|
||||
// 钱包(ADB)与 sqlnet.ora 都依赖这个目录,任何 OCI 连接都可以不经过
|
||||
// TNS 连接方式直接使用它们;目录同样无法在连接建立后更改。
|
||||
let tns_admin = crate::oracle_oci::resolve_oci_tns_admin(
|
||||
config.oracle_oci_tns_admin.as_deref(),
|
||||
config.connection_string.as_deref(),
|
||||
defaults.tns_admin.as_deref(),
|
||||
);
|
||||
crate::oracle_oci::oracle_oci_launch_env(nls_lang, defaults.client_path.as_deref(), tns_admin.as_deref())
|
||||
}
|
||||
|
||||
/// Reads the global Oracle OCI defaults from editor settings.
|
||||
///
|
||||
/// Editor settings are one opaque JSON blob owned by the frontend, so a
|
||||
/// missing or malformed value degrades to "unset" rather than failing the
|
||||
/// connection.
|
||||
async fn oracle_oci_defaults(&self) -> OracleOciDefaults {
|
||||
let Ok(Some(settings)) = self.storage.load_editor_settings().await else {
|
||||
return OracleOciDefaults::default();
|
||||
};
|
||||
OracleOciDefaults {
|
||||
nls_lang: json_trimmed_string(&settings, "oracleOciNlsLang"),
|
||||
client_path: json_trimmed_string(&settings, "oracleOciClientPath"),
|
||||
tns_admin: json_trimmed_string(&settings, "oracleOciTnsAdmin"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn spawn_routed_shared_agent_client(
|
||||
&self,
|
||||
db_type: &DatabaseType,
|
||||
driver_profile: Option<&str>,
|
||||
extra_java_args: &[String],
|
||||
agent_env: &[(String, String)],
|
||||
agent_session_id: String,
|
||||
connect_params: serde_json::Value,
|
||||
connect_timeout: Duration,
|
||||
@@ -1571,6 +1634,7 @@ impl AppState {
|
||||
db_type,
|
||||
driver_profile,
|
||||
extra_java_args,
|
||||
agent_env,
|
||||
agent_session_id,
|
||||
connect_params,
|
||||
connect_timeout,
|
||||
@@ -3018,11 +3082,13 @@ impl AppState {
|
||||
)?;
|
||||
if db_config.db_type != DatabaseType::ZooKeeper {
|
||||
let agent_session_id = uuid::Uuid::new_v4().simple().to_string();
|
||||
let agent_env = self.agent_launch_env(&db_config).await;
|
||||
let mut initial_result = self
|
||||
.spawn_routed_shared_agent_client(
|
||||
&db_config.db_type,
|
||||
db_config.driver_profile.as_deref(),
|
||||
&db_config.agent_java_options,
|
||||
&agent_env,
|
||||
agent_session_id.clone(),
|
||||
connect_params,
|
||||
agent_connect_timeout(&db_config),
|
||||
@@ -3043,6 +3109,7 @@ impl AppState {
|
||||
&db_config.db_type,
|
||||
db_config.driver_profile.as_deref(),
|
||||
&db_config.agent_java_options,
|
||||
&agent_env,
|
||||
agent_session_id.clone(),
|
||||
agent_connect_params_with_role(
|
||||
&db_config,
|
||||
@@ -3106,11 +3173,13 @@ impl AppState {
|
||||
alternate_config.effective_database().unwrap_or(""),
|
||||
session_role,
|
||||
)?;
|
||||
let alternate_env = self.agent_launch_env(&alternate_config).await;
|
||||
match self
|
||||
.spawn_routed_shared_agent_client(
|
||||
&alternate_config.db_type,
|
||||
alternate_config.driver_profile.as_deref(),
|
||||
&alternate_config.agent_java_options,
|
||||
&alternate_env,
|
||||
agent_session_id.clone(),
|
||||
alternate_params,
|
||||
agent_connect_timeout(&alternate_config),
|
||||
@@ -7051,6 +7120,8 @@ mod tests {
|
||||
|
||||
fn mysql_config(database: Option<&str>) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "conn".to_string(),
|
||||
name: "MySQL".to_string(),
|
||||
@@ -9553,6 +9624,8 @@ sleep 30
|
||||
client_key_path: String::new(),
|
||||
sysdba: false,
|
||||
oracle_connection_type: None,
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
connection_string: None,
|
||||
redis_connection_mode: None,
|
||||
redis_sentinel_master: String::new(),
|
||||
|
||||
@@ -11868,6 +11868,8 @@ for line in sys.stdin:
|
||||
|
||||
fn jdbc_transfer_config(connection_string: &str, driver_class: &str, profile: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
id: "test-jdbc".to_string(),
|
||||
name: "Test JDBC".to_string(),
|
||||
note: String::new(),
|
||||
@@ -18140,6 +18142,8 @@ SELECT 1 FROM dual"#
|
||||
#[test]
|
||||
fn resolve_external_transfer_catalog_for_config_accepts_starrocks_driver_profile() {
|
||||
let config = crate::models::connection::ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "sr".to_string(),
|
||||
name: "sr".to_string(),
|
||||
|
||||
@@ -27,6 +27,7 @@ pub use dbx_drivers::agent_recovery;
|
||||
pub use dbx_drivers::agent_runtime;
|
||||
pub use dbx_drivers::agent_service;
|
||||
pub use dbx_drivers::backend_error;
|
||||
pub use dbx_drivers::oracle_oci;
|
||||
pub use host::changelog;
|
||||
pub use persistence::cloud_sync;
|
||||
pub use persistence::config;
|
||||
|
||||
@@ -3440,6 +3440,8 @@ mod tests {
|
||||
|
||||
fn postgres_connection(id: &str, password: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: "Postgres".to_string(),
|
||||
@@ -3524,6 +3526,8 @@ mod tests {
|
||||
|
||||
fn nacos_connection(id: &str, password: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: "Nacos".to_string(),
|
||||
@@ -3764,6 +3768,8 @@ mod tests {
|
||||
#[test]
|
||||
fn scrubs_connection_secret_fields() {
|
||||
let mut config = ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "id".to_string(),
|
||||
name: "name".to_string(),
|
||||
|
||||
@@ -10773,6 +10773,8 @@ mod tests {
|
||||
|
||||
fn mq_connection(id: &str, token: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: "Pulsar".to_string(),
|
||||
@@ -10848,6 +10850,8 @@ mod tests {
|
||||
|
||||
fn nacos_connection(id: &str, password: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: "Nacos".to_string(),
|
||||
@@ -11071,7 +11075,10 @@ mod tests {
|
||||
let target_dir = temp_data_dir("import-empty-target");
|
||||
std::fs::create_dir_all(managed_key_path(&target_dir).parent().unwrap()).unwrap();
|
||||
std::fs::copy(managed_key_path(&source_dir), managed_key_path(&target_dir)).unwrap();
|
||||
let _target_storage = crate::persistence::test_storage::open(&target_dir.join("dbx.db")).await.unwrap();
|
||||
// 打开一次以创建空目标库;导入前必须释放,否则 Windows 上目标文件被占用、
|
||||
// 替换会失败(与相邻用例一致)。
|
||||
let target_storage = crate::persistence::test_storage::open(&target_dir.join("dbx.db")).await.unwrap();
|
||||
drop(target_storage);
|
||||
|
||||
let result = maybe_import_user_data_db(&target_dir, Some(&source_dir)).unwrap();
|
||||
|
||||
|
||||
@@ -8047,6 +8047,8 @@ for line in sys.stdin:
|
||||
|
||||
fn test_connection_config(db_type: DatabaseType) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "conn-1".to_string(),
|
||||
name: "Connection".to_string(),
|
||||
@@ -10889,6 +10891,8 @@ for line in sys.stdin:
|
||||
#[test]
|
||||
fn external_driver_query_params_include_database_and_schema_context() {
|
||||
let config = ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "jdbc-1".to_string(),
|
||||
name: "JDBC".to_string(),
|
||||
|
||||
@@ -758,6 +758,8 @@ mod tests {
|
||||
|
||||
fn config() -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "conn".to_string(),
|
||||
name: "test".to_string(),
|
||||
|
||||
@@ -3291,6 +3291,8 @@ mod tests {
|
||||
|
||||
fn test_connection_config(db_type: DatabaseType) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "test".to_string(),
|
||||
name: "test".to_string(),
|
||||
|
||||
@@ -145,6 +145,8 @@ mod tests {
|
||||
|
||||
fn test_connection_config(db_type: DatabaseType) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
id: "test".to_string(),
|
||||
name: "test".to_string(),
|
||||
db_type,
|
||||
|
||||
@@ -175,6 +175,104 @@ fn registry_with_native_driver(db_type: &str, version: &str, jre: &str) -> Agent
|
||||
AgentRegistry { jre: None, jres: std::collections::HashMap::new(), drivers }
|
||||
}
|
||||
|
||||
/// A native-only driver the registry publishes for every platform *except* this
|
||||
/// one, mirroring the Windows-only Oracle OCI agent on macOS and Linux.
|
||||
fn registry_with_foreign_platform_native_driver(db_type: &str, version: &str) -> AgentRegistry {
|
||||
let current = AgentManager::current_platform();
|
||||
let native = ["macos-aarch64", "macos-x64", "linux-aarch64", "linux-x64", "windows-aarch64", "windows-x64"]
|
||||
.into_iter()
|
||||
.filter(|platform| *platform != current)
|
||||
.map(|platform| {
|
||||
(
|
||||
platform.to_string(),
|
||||
ArtifactInfo {
|
||||
url: format!("https://example.com/dbx-agent-{db_type}-{platform}"),
|
||||
sha256: None,
|
||||
size: 42,
|
||||
format: None,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut drivers = std::collections::HashMap::new();
|
||||
drivers.insert(
|
||||
db_type.to_string(),
|
||||
DriverInfo {
|
||||
version: version.to_string(),
|
||||
label: db_type.to_string(),
|
||||
min_app_version: "0.1.0".to_string(),
|
||||
jre: DEFAULT_JRE_KEY.to_string(),
|
||||
// Native-only drivers still carry a zero-size legacy JAR placeholder,
|
||||
// which must not be mistaken for an installable fallback.
|
||||
jar: Some(ArtifactInfo {
|
||||
url: format!("https://example.com/dbx-agent-{db_type}-legacy-placeholder.jar"),
|
||||
sha256: None,
|
||||
size: 0,
|
||||
format: None,
|
||||
}),
|
||||
native,
|
||||
},
|
||||
);
|
||||
AgentRegistry { jre: None, jres: std::collections::HashMap::new(), drivers }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_list_hides_a_driver_the_registry_publishes_for_other_platforms_only() {
|
||||
let manager = test_manager("foreign-platform-hidden");
|
||||
let registry = registry_with_foreign_platform_native_driver("oracle-oci", "0.1.0");
|
||||
|
||||
let agents = build_agent_list(&manager, Some(®istry));
|
||||
|
||||
assert!(
|
||||
!agents.iter().any(|agent| agent.db_type == "oracle-oci"),
|
||||
"a driver with no artifact for this platform must not be offered for install"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_list_keeps_an_installed_driver_the_registry_publishes_for_other_platforms_only() {
|
||||
let manager = test_manager("foreign-platform-installed");
|
||||
let native_path = manager.driver_native_path("oracle-oci");
|
||||
std::fs::create_dir_all(native_path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&native_path, b"agent").unwrap();
|
||||
manager
|
||||
.save_state(&dbx_core::agent_manager::AgentState {
|
||||
installed_drivers: [(
|
||||
"oracle-oci".to_string(),
|
||||
InstalledDriver {
|
||||
version: "0.1.0".to_string(),
|
||||
installed_at: "2026-05-18T00:00:00Z".to_string(),
|
||||
jre: DEFAULT_JRE_KEY.to_string(),
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
let registry = registry_with_foreign_platform_native_driver("oracle-oci", "0.1.0");
|
||||
|
||||
let agents = build_agent_list(&manager, Some(®istry));
|
||||
|
||||
let oci = agents
|
||||
.iter()
|
||||
.find(|agent| agent.db_type == "oracle-oci")
|
||||
.expect("an installed driver must stay listed so it can be upgraded or removed");
|
||||
assert!(oci.installed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_list_keeps_the_sqlite_worker_although_its_binaries_target_another_platform() {
|
||||
// The SSH worker executes on the remote host, so a `native` set without a
|
||||
// desktop platform must not hide it (#8987).
|
||||
let manager = test_manager("sqlite-worker-platform-gate");
|
||||
let registry = registry_with_foreign_platform_native_driver("sqlite-worker", "0.1.0");
|
||||
|
||||
let agents = build_agent_list(&manager, Some(®istry));
|
||||
|
||||
assert!(agents.iter().any(|agent| agent.db_type == "sqlite-worker"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn built_in_agent_list_includes_expected_driver_labels() {
|
||||
let manager = test_manager("labels");
|
||||
|
||||
@@ -6,6 +6,8 @@ use std::str::FromStr;
|
||||
|
||||
fn mysql_config(username: &str, password: &str, database: Option<&str>) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "id".to_string(),
|
||||
name: "name".to_string(),
|
||||
|
||||
@@ -21,6 +21,8 @@ fn live_postgres_config(
|
||||
database: &str,
|
||||
) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -17,6 +17,8 @@ fn live_postgres_config(
|
||||
database: &str,
|
||||
) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -12,6 +12,8 @@ fn live_postgres_config(
|
||||
database: &str,
|
||||
) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -166,6 +166,8 @@ fn live_connection_config(
|
||||
database: &str,
|
||||
) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -17,6 +17,8 @@ fn live_postgres_config(
|
||||
database: &str,
|
||||
) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -11,6 +11,8 @@ use std::sync::Arc;
|
||||
|
||||
fn postgres_test_config(id: &str, database: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -16,6 +16,8 @@ use std::time::Duration;
|
||||
|
||||
fn sqlite_config(id: &str, path: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -18,6 +18,8 @@ use tokio_util::sync::CancellationToken;
|
||||
|
||||
fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connection::ConnectionConfig {
|
||||
dbx_core::models::connection::ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -7,6 +7,8 @@ use std::time::{Duration, Instant};
|
||||
|
||||
fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connection::ConnectionConfig {
|
||||
dbx_core::models::connection::ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -22,6 +22,8 @@ use tokio_util::sync::CancellationToken;
|
||||
|
||||
fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connection::ConnectionConfig {
|
||||
dbx_core::models::connection::ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -10,6 +10,8 @@ use std::time::Duration;
|
||||
|
||||
fn live_sqlserver_config(id: &str, database: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -132,6 +132,8 @@ pub fn psql_allow_failure(container: &DockerPostgres, sql: &str) -> bool {
|
||||
|
||||
pub fn postgres_test_config(id: &str, port: u16) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
|
||||
@@ -415,6 +415,9 @@ pub fn oracle_alternate_connect_configs(config: &ConnectionConfig, err: &str) ->
|
||||
_ => vec![sid_url, legacy_service_url, descriptor_service_url, descriptor_sid_url],
|
||||
}
|
||||
};
|
||||
// The retries travel through `oracle_jdbc_connection_string` as a stored
|
||||
// connection string, so they must already carry the profile's protocol.
|
||||
let candidates: Vec<String> = candidates.into_iter().map(|url| oracle_url_for_profile(config, url)).collect();
|
||||
|
||||
let mut urls = Vec::new();
|
||||
for url in candidates {
|
||||
@@ -434,6 +437,20 @@ pub fn oracle_alternate_connect_configs(config: &ConnectionConfig, err: &str) ->
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Applies the OCI (thick) protocol to an Oracle JDBC URL when the connection
|
||||
/// selects the OCI driver profile. Thin connections keep the URL unchanged.
|
||||
///
|
||||
/// OCI reaches the same targets as thin; the TNS form additionally moves its
|
||||
/// `TNS_ADMIN` query into the agent-process environment
|
||||
/// (`crate::oracle_oci::oracle_oci_launch_env`).
|
||||
fn oracle_url_for_profile(config: &ConnectionConfig, url: String) -> String {
|
||||
if !crate::oracle_oci::uses_oracle_oci_profile(config) {
|
||||
return url;
|
||||
}
|
||||
let rewritten = crate::oracle_oci::rewrite_oracle_url_protocol(&url, true);
|
||||
crate::oracle_oci::strip_oracle_tns_admin_query(&rewritten)
|
||||
}
|
||||
|
||||
fn oracle_jdbc_connection_string(
|
||||
config: &ConnectionConfig,
|
||||
host: &str,
|
||||
@@ -443,9 +460,12 @@ fn oracle_jdbc_connection_string(
|
||||
if let Some(connection_string) = config.connection_string.as_deref().filter(|value| !value.trim().is_empty()) {
|
||||
let connection_string = connection_string.trim();
|
||||
if host == config.host && port == config.port {
|
||||
return Ok(connection_string.to_string());
|
||||
return Ok(oracle_url_for_profile(config, connection_string.to_string()));
|
||||
}
|
||||
return crate::models::connection::rewrite_jdbc_url_host(connection_string, host, port);
|
||||
return Ok(oracle_url_for_profile(
|
||||
config,
|
||||
crate::models::connection::rewrite_jdbc_url_host(connection_string, host, port)?,
|
||||
));
|
||||
}
|
||||
|
||||
let database = database.trim();
|
||||
@@ -453,11 +473,12 @@ fn oracle_jdbc_connection_string(
|
||||
return Ok(String::new());
|
||||
}
|
||||
|
||||
Ok(if config.oracle_connection_type.as_deref() == Some("sid") {
|
||||
let url = if config.oracle_connection_type.as_deref() == Some("sid") {
|
||||
oracle_sid_jdbc_url(host, port, database)
|
||||
} else {
|
||||
oracle_service_jdbc_url(host, port, database)
|
||||
})
|
||||
};
|
||||
Ok(oracle_url_for_profile(config, url))
|
||||
}
|
||||
|
||||
fn oracle_listener_error_can_retry(err: &str) -> bool {
|
||||
@@ -764,6 +785,8 @@ mod tests {
|
||||
|
||||
fn config(db_type: DatabaseType, database: Option<&str>) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "conn".to_string(),
|
||||
name: "Connection".to_string(),
|
||||
@@ -888,6 +911,60 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oracle_oci_profile_builds_oci8_urls_for_service_and_sid() {
|
||||
for (mode, expected_url) in [
|
||||
("service_name", "jdbc:oracle:oci8:@//oracle.example.com:1521/ORCLPDB1"),
|
||||
("sid", "jdbc:oracle:oci8:@oracle.example.com:1521:ORCLPDB1"),
|
||||
] {
|
||||
let mut cfg = config(DatabaseType::Oracle, Some("ORCLPDB1"));
|
||||
cfg.driver_profile = Some(crate::oracle_oci::ORACLE_OCI_DRIVER_PROFILE.to_string());
|
||||
cfg.oracle_connection_type = Some(mode.to_string());
|
||||
|
||||
let params = agent_connect_params(&cfg, "oracle.example.com", 1521, "ORCLPDB1").unwrap();
|
||||
|
||||
assert_eq!(params["connection_string"], expected_url);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oracle_oci_profile_rewrites_tns_urls_and_strips_the_admin_query() {
|
||||
let mut cfg = config(DatabaseType::Oracle, None);
|
||||
cfg.driver_profile = Some(crate::oracle_oci::ORACLE_OCI_DRIVER_PROFILE.to_string());
|
||||
cfg.connection_string = Some("jdbc:oracle:oci8:@ORCLPDB1?TNS_ADMIN=C%3A%5Coracle%5Cwallets".to_string());
|
||||
|
||||
// 主机与端口沿用连接自身:TNS 别名 URL 不参与主机改写(别名没有 host)。
|
||||
let params = agent_connect_params(&cfg, &cfg.host.clone(), cfg.port, "").unwrap();
|
||||
|
||||
assert_eq!(params["connection_string"], "jdbc:oracle:oci8:@ORCLPDB1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oracle_thin_profile_keeps_the_thin_protocol() {
|
||||
let mut cfg = config(DatabaseType::Oracle, Some("ORCLPDB1"));
|
||||
cfg.oracle_connection_type = Some("service_name".to_string());
|
||||
|
||||
let params = agent_connect_params(&cfg, "oracle.example.com", 1521, "ORCLPDB1").unwrap();
|
||||
|
||||
assert_eq!(params["connection_string"], "jdbc:oracle:thin:@//oracle.example.com:1521/ORCLPDB1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oracle_oci_alternate_connect_configs_stay_on_the_oci_protocol() {
|
||||
let mut cfg = config(DatabaseType::Oracle, Some("ORCLPDB1"));
|
||||
cfg.driver_profile = Some(crate::oracle_oci::ORACLE_OCI_DRIVER_PROFILE.to_string());
|
||||
cfg.oracle_connection_type = Some("service_name".to_string());
|
||||
|
||||
let alternates =
|
||||
oracle_alternate_connect_configs(&cfg, "ORA-12514: listener does not currently know of service");
|
||||
|
||||
assert!(!alternates.is_empty());
|
||||
for alternate in &alternates {
|
||||
let url = alternate.connection_string.as_deref().expect("alternate url");
|
||||
assert!(url.starts_with("jdbc:oracle:oci8:@"), "alternate url must keep the oci8 protocol: {url}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structured_hive_uses_current_url_params_for_zookeeper_detection() {
|
||||
let mut cfg = config(DatabaseType::Hive, Some("default"));
|
||||
|
||||
@@ -962,16 +962,24 @@ impl PooledAgentClient {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AgentLaunchSpec {
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub working_dir: Option<PathBuf>,
|
||||
/// Extra environment variables handed to the agent process.
|
||||
///
|
||||
/// This is part of the launch *identity*, not just the launch mechanics:
|
||||
/// [`crate::agent_runtime::shared_runtime_key`] hashes it, so two launches
|
||||
/// that differ only in `env` get separate agent processes. That is what
|
||||
/// makes process-scoped Oracle Client settings (`NLS_LANG`) safe to set per
|
||||
/// connection instead of leaking across connections that share a process.
|
||||
pub env: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl AgentLaunchSpec {
|
||||
pub fn new(program: impl Into<PathBuf>) -> Self {
|
||||
Self { program: program.into(), args: Vec::new(), working_dir: None }
|
||||
Self { program: program.into(), args: Vec::new(), working_dir: None, env: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn java_jar(java_path: impl Into<PathBuf>, jar_path: impl AsRef<Path>) -> Self {
|
||||
@@ -988,6 +996,7 @@ impl AgentLaunchSpec {
|
||||
program: java_path.into(),
|
||||
args: agent_java_args_with_extra_args(&jar_path.to_string_lossy(), extra_java_args),
|
||||
working_dir: jar_path.parent().map(Path::to_path_buf),
|
||||
env: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1000,6 +1009,15 @@ impl AgentLaunchSpec {
|
||||
self.working_dir = Some(working_dir.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Appends `env` after any entries already present.
|
||||
///
|
||||
/// Later entries win when [`Self::env`] is applied to the child process,
|
||||
/// so callers can layer connection-level overrides on top of defaults.
|
||||
pub fn with_env(mut self, env: impl IntoIterator<Item = (String, String)>) -> Self {
|
||||
self.env.extend(env);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
@@ -3320,6 +3338,9 @@ fn agent_command(launch: &AgentLaunchSpec) -> Command {
|
||||
command.current_dir(working_dir);
|
||||
}
|
||||
remove_agent_proxy_env(&mut command);
|
||||
// Applied after the proxy scrub so an explicitly configured variable (for
|
||||
// example an Oracle Client path) is never silently dropped.
|
||||
command.envs(launch.env.iter().map(|(key, value)| (key.as_str(), value.as_str())));
|
||||
command
|
||||
}
|
||||
|
||||
|
||||
@@ -607,10 +607,11 @@ mod tests {
|
||||
.expect("manifest launch should resolve");
|
||||
|
||||
assert_eq!(launch.program, driver_dir.join("bin").join("dameng-agent"));
|
||||
assert_eq!(
|
||||
launch.args,
|
||||
vec!["--config".to_string(), driver_dir.join("config.json").to_string_lossy().to_string()]
|
||||
);
|
||||
// 比较 Path:模板里写的是正斜杠,而 Path::join 在 Windows 上产出反斜杠,
|
||||
// 直接比字符串会在 Windows 上误报。
|
||||
assert_eq!(launch.args.len(), 2);
|
||||
assert_eq!(launch.args[0], "--config");
|
||||
assert_eq!(std::path::PathBuf::from(&launch.args[1]), driver_dir.join("config.json"));
|
||||
assert_eq!(launch.working_dir.as_deref(), Some(driver_dir.as_path()));
|
||||
}
|
||||
|
||||
@@ -1122,6 +1123,22 @@ impl AgentManager {
|
||||
driver_key: &str,
|
||||
jre_key: &str,
|
||||
extra_java_args: &[String],
|
||||
) -> Result<AgentLaunchSpec, String> {
|
||||
self.resolve_agent_launch_spec_with_launch_env(state, driver_key, jre_key, extra_java_args, &[])
|
||||
}
|
||||
|
||||
/// Same as [`Self::resolve_agent_launch_spec_with_extra_args`] but also
|
||||
/// attaches `env` to the resolved spec.
|
||||
///
|
||||
/// The entries become part of the launch fingerprint, so two connections
|
||||
/// requesting different environments never share an agent process.
|
||||
pub fn resolve_agent_launch_spec_with_launch_env(
|
||||
&self,
|
||||
state: &AgentState,
|
||||
driver_key: &str,
|
||||
jre_key: &str,
|
||||
extra_java_args: &[String],
|
||||
env: &[(String, String)],
|
||||
) -> Result<AgentLaunchSpec, String> {
|
||||
if driver_key == "dameng" {
|
||||
validate_dameng_java_system_properties(extra_java_args)?;
|
||||
@@ -1129,7 +1146,9 @@ impl AgentManager {
|
||||
let driver_dir = self.driver_dir(driver_key);
|
||||
let config_path = self.driver_launch_config_path(driver_key);
|
||||
if config_path.exists() {
|
||||
return self.resolve_configured_agent_launch_spec(driver_key, &driver_dir, &config_path);
|
||||
return Ok(self
|
||||
.resolve_configured_agent_launch_spec(driver_key, &driver_dir, &config_path)?
|
||||
.with_env(env.iter().cloned()));
|
||||
}
|
||||
|
||||
let native_path = self.driver_native_path(driver_key);
|
||||
@@ -1145,7 +1164,7 @@ impl AgentManager {
|
||||
} else {
|
||||
(native_path, driver_dir)
|
||||
};
|
||||
return Ok(AgentLaunchSpec::new(native_path).with_working_dir(driver_dir));
|
||||
return Ok(AgentLaunchSpec::new(native_path).with_working_dir(driver_dir).with_env(env.iter().cloned()));
|
||||
}
|
||||
|
||||
let jar_path = self.driver_jar_path(driver_key);
|
||||
@@ -1156,7 +1175,8 @@ impl AgentManager {
|
||||
"{driver_key} driver jar is invalid or corrupt. Please reinstall it from the Driver Manager."
|
||||
));
|
||||
}
|
||||
return Ok(AgentLaunchSpec::java_jar_with_extra_args(java, jar_path, extra_java_args));
|
||||
return Ok(AgentLaunchSpec::java_jar_with_extra_args(java, jar_path, extra_java_args)
|
||||
.with_env(env.iter().cloned()));
|
||||
}
|
||||
|
||||
Err(format!("{driver_key} driver is not installed. Please install it from the Driver Manager."))
|
||||
@@ -1364,11 +1384,44 @@ impl AgentManager {
|
||||
crate::agent_runtime::spawn_connection_client(self, db_type, driver_profile, extra_java_args).await
|
||||
}
|
||||
|
||||
/// Spawns a dedicated agent process carrying `env` (Oracle OCI connections).
|
||||
pub async fn spawn_with_env(
|
||||
&self,
|
||||
db_type: &DatabaseType,
|
||||
driver_profile: Option<&str>,
|
||||
env: &[(String, String)],
|
||||
) -> Result<AgentDriverClient, String> {
|
||||
crate::agent_runtime::spawn_connection_client_with_env(self, db_type, driver_profile, &[], env).await
|
||||
}
|
||||
|
||||
/// One-shot daemon call variant that hands `env` to the agent process.
|
||||
pub async fn call_daemon_method_with_timeout_and_env<T: serde::de::DeserializeOwned + Send + 'static>(
|
||||
&self,
|
||||
db_type: &DatabaseType,
|
||||
driver_profile: Option<&str>,
|
||||
method: AgentMethod,
|
||||
params: serde_json::Value,
|
||||
timeout_duration: Option<Duration>,
|
||||
env: &[(String, String)],
|
||||
) -> Result<T, String> {
|
||||
crate::agent_runtime::call_daemon_method_with_timeout_and_env(
|
||||
self,
|
||||
db_type,
|
||||
driver_profile,
|
||||
method,
|
||||
params,
|
||||
timeout_duration,
|
||||
env,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn spawn_shared_connection_client(
|
||||
&self,
|
||||
db_type: &DatabaseType,
|
||||
driver_profile: Option<&str>,
|
||||
extra_java_args: &[String],
|
||||
agent_env: &[(String, String)],
|
||||
agent_session_id: String,
|
||||
connect_params: serde_json::Value,
|
||||
connect_timeout: std::time::Duration,
|
||||
@@ -1378,6 +1431,7 @@ impl AgentManager {
|
||||
db_type,
|
||||
driver_profile,
|
||||
extra_java_args,
|
||||
agent_env,
|
||||
agent_session_id,
|
||||
connect_params,
|
||||
connect_timeout,
|
||||
|
||||
@@ -52,7 +52,7 @@ pub async fn stop_daemon_by_key(manager: &AgentManager, agent_key: &str) {
|
||||
|
||||
pub async fn restart_daemon_by_key(manager: &AgentManager, agent_key: &str) -> Result<(), String> {
|
||||
manager.daemons.lock().await.remove(agent_key);
|
||||
let client = spawn_client_for_key(manager, agent_key, &[]).await?;
|
||||
let client = spawn_client_for_key(manager, agent_key, &[], &[]).await?;
|
||||
manager.daemons.lock().await.insert(agent_key.to_string(), client);
|
||||
Ok(())
|
||||
}
|
||||
@@ -62,10 +62,26 @@ pub async fn spawn_connection_client(
|
||||
db_type: &DatabaseType,
|
||||
driver_profile: Option<&str>,
|
||||
extra_java_args: &[String],
|
||||
) -> Result<AgentDriverClient, String> {
|
||||
spawn_connection_client_with_env(manager, db_type, driver_profile, extra_java_args, &[]).await
|
||||
}
|
||||
|
||||
/// Spawns a dedicated agent process whose environment carries `env`.
|
||||
///
|
||||
/// Oracle OCI ("thick") connections use this to hand process-scoped client
|
||||
/// settings (`NLS_LANG`, the Instant Client loader directory) to the agent:
|
||||
/// those cannot travel as connection parameters, and two connections that
|
||||
/// disagree about them must never share one process.
|
||||
pub async fn spawn_connection_client_with_env(
|
||||
manager: &AgentManager,
|
||||
db_type: &DatabaseType,
|
||||
driver_profile: Option<&str>,
|
||||
extra_java_args: &[String],
|
||||
env: &[(String, String)],
|
||||
) -> Result<AgentDriverClient, String> {
|
||||
let keys = runtime_agent_key_candidates(db_type, driver_profile)
|
||||
.ok_or_else(|| format!("{:?} is not an agent-driven database type", db_type))?;
|
||||
spawn_first_available_client(manager, &keys, extra_java_args).await
|
||||
spawn_first_available_client(manager, &keys, extra_java_args, env).await
|
||||
}
|
||||
|
||||
pub async fn spawn_shared_connection_client(
|
||||
@@ -73,6 +89,7 @@ pub async fn spawn_shared_connection_client(
|
||||
db_type: &DatabaseType,
|
||||
driver_profile: Option<&str>,
|
||||
extra_java_args: &[String],
|
||||
agent_env: &[(String, String)],
|
||||
agent_session_id: String,
|
||||
connect_params: serde_json::Value,
|
||||
connect_timeout: Duration,
|
||||
@@ -82,7 +99,7 @@ pub async fn spawn_shared_connection_client(
|
||||
let key = first_installed_agent_key(manager, &keys).unwrap_or(keys[0]);
|
||||
let state = manager.load_state();
|
||||
let jre_key = state.installed_drivers.get(key).map(|driver| driver.jre.as_str()).unwrap_or(DEFAULT_JRE_KEY);
|
||||
let launch = manager.resolve_agent_launch_spec_with_extra_args(&state, key, jre_key, extra_java_args)?;
|
||||
let launch = manager.resolve_agent_launch_spec_with_launch_env(&state, key, jre_key, extra_java_args, agent_env)?;
|
||||
let runtime_key = shared_runtime_key(key, &launch);
|
||||
let mut session_params = connect_params;
|
||||
session_params
|
||||
@@ -178,12 +195,17 @@ fn reserve_runtime_locked(
|
||||
}
|
||||
|
||||
fn shared_runtime_key(agent_key: &str, launch: &crate::db::agent_driver::AgentLaunchSpec) -> String {
|
||||
// `env` is part of the fingerprint on purpose: Oracle Client settings such
|
||||
// as `NLS_LANG` are process-scoped, so a connection that declares one must
|
||||
// not reuse a process started without it (or with a different value).
|
||||
let env = launch.env.iter().map(|(key, value)| format!("{key}={value}")).collect::<Vec<_>>().join("\u{1f}");
|
||||
format!(
|
||||
"{}|{}|{}|{}",
|
||||
"{}|{}|{}|{}|{}",
|
||||
agent_key,
|
||||
launch.program.display(),
|
||||
launch.args.join("\u{1f}"),
|
||||
launch.working_dir.as_ref().map(|path| path.display().to_string()).unwrap_or_default()
|
||||
launch.working_dir.as_ref().map(|path| path.display().to_string()).unwrap_or_default(),
|
||||
env
|
||||
)
|
||||
}
|
||||
|
||||
@@ -201,7 +223,7 @@ pub async fn call_daemon<T: DeserializeOwned + Send + 'static>(
|
||||
let mut daemons = manager.daemons.lock().await;
|
||||
|
||||
if !daemons.contains_key(&key) {
|
||||
let client = spawn_client_for_key(manager, &key, &[]).await?;
|
||||
let client = spawn_client_for_key(manager, &key, &[], &[]).await?;
|
||||
daemons.insert(key.clone(), client);
|
||||
}
|
||||
|
||||
@@ -211,7 +233,7 @@ pub async fn call_daemon<T: DeserializeOwned + Send + 'static>(
|
||||
Err(err) => {
|
||||
log::warn!("[agent] daemon call failed, respawning: {err}");
|
||||
daemons.remove(&key);
|
||||
let mut new_client = spawn_client_for_key(manager, &key, &[]).await?;
|
||||
let mut new_client = spawn_client_for_key(manager, &key, &[], &[]).await?;
|
||||
let result = new_client.call::<T>(method, params).await?;
|
||||
daemons.insert(key, new_client);
|
||||
Ok(result)
|
||||
@@ -234,7 +256,7 @@ pub async fn call_daemon_with_timeout<T: DeserializeOwned + Send + 'static>(
|
||||
let mut daemons = manager.daemons.lock().await;
|
||||
|
||||
if !daemons.contains_key(&key) {
|
||||
let client = spawn_client_for_key(manager, &key, &[]).await?;
|
||||
let client = spawn_client_for_key(manager, &key, &[], &[]).await?;
|
||||
daemons.insert(key.clone(), client);
|
||||
}
|
||||
|
||||
@@ -244,7 +266,7 @@ pub async fn call_daemon_with_timeout<T: DeserializeOwned + Send + 'static>(
|
||||
Err(err) => {
|
||||
log::warn!("[agent] daemon call failed, respawning: {err}");
|
||||
daemons.remove(&key);
|
||||
let mut new_client = spawn_client_for_key(manager, &key, &[]).await?;
|
||||
let mut new_client = spawn_client_for_key(manager, &key, &[], &[]).await?;
|
||||
let result = new_client.call_with_timeout::<T>(method, params, timeout_duration).await?;
|
||||
daemons.insert(key, new_client);
|
||||
Ok(result)
|
||||
@@ -273,6 +295,32 @@ pub async fn call_daemon_method_with_timeout<T: DeserializeOwned + Send + 'stati
|
||||
call_daemon_with_timeout(manager, db_type, driver_profile, method.as_str(), params, timeout_duration).await
|
||||
}
|
||||
|
||||
/// Environment-aware sibling of [`call_daemon_method_with_timeout`].
|
||||
///
|
||||
/// A non-empty `env` gets a dedicated, short-lived process instead of the
|
||||
/// shared per-key daemon: process-scoped Oracle OCI settings (`NLS_LANG`, the
|
||||
/// Instant Client loader directory) must not leak into a process another
|
||||
/// connection is already using.
|
||||
pub async fn call_daemon_method_with_timeout_and_env<T: DeserializeOwned + Send + 'static>(
|
||||
manager: &AgentManager,
|
||||
db_type: &DatabaseType,
|
||||
driver_profile: Option<&str>,
|
||||
method: AgentMethod,
|
||||
params: serde_json::Value,
|
||||
timeout_duration: Option<Duration>,
|
||||
env: &[(String, String)],
|
||||
) -> Result<T, String> {
|
||||
if env.is_empty() {
|
||||
return call_daemon_with_timeout(manager, db_type, driver_profile, method.as_str(), params, timeout_duration)
|
||||
.await;
|
||||
}
|
||||
let keys = runtime_agent_key_candidates(db_type, driver_profile)
|
||||
.ok_or_else(|| format!("{:?} is not an agent-driven database type", db_type))?;
|
||||
let key = first_installed_agent_key(manager, &keys).unwrap_or(keys[0]).to_string();
|
||||
let mut client = spawn_client_for_key(manager, &key, &[], env).await?;
|
||||
client.call_with_timeout::<T>(method.as_str(), params, timeout_duration).await
|
||||
}
|
||||
|
||||
fn runtime_agent_key_candidates(db_type: &DatabaseType, driver_profile: Option<&str>) -> Option<Vec<&'static str>> {
|
||||
let primary = db_type_to_agent_key(db_type, driver_profile)?;
|
||||
Some(vec![primary])
|
||||
@@ -284,12 +332,13 @@ fn first_installed_agent_key<'a>(manager: &AgentManager, keys: &'a [&'static str
|
||||
|
||||
async fn spawn_first_available_client(
|
||||
manager: &AgentManager,
|
||||
keys: &[&'static str],
|
||||
keys: &[&str],
|
||||
extra_java_args: &[String],
|
||||
env: &[(String, String)],
|
||||
) -> Result<AgentDriverClient, String> {
|
||||
let mut last_error = None;
|
||||
for key in keys {
|
||||
match spawn_client_for_key(manager, key, extra_java_args).await {
|
||||
match spawn_client_for_key(manager, key, extra_java_args, env).await {
|
||||
Ok(client) => return Ok(client),
|
||||
Err(err) => last_error = Some(err),
|
||||
}
|
||||
@@ -301,11 +350,14 @@ async fn spawn_client_for_key(
|
||||
manager: &AgentManager,
|
||||
key: &str,
|
||||
extra_java_args: &[String],
|
||||
env: &[(String, String)],
|
||||
) -> Result<AgentDriverClient, String> {
|
||||
let state = manager.load_state();
|
||||
let jre_key = state.installed_drivers.get(key).map(|driver| driver.jre.as_str()).unwrap_or(DEFAULT_JRE_KEY);
|
||||
|
||||
let launch = manager.resolve_agent_launch_spec_with_extra_args(&state, key, jre_key, extra_java_args)?;
|
||||
let launch = manager
|
||||
.resolve_agent_launch_spec_with_extra_args(&state, key, jre_key, extra_java_args)?
|
||||
.with_env(env.iter().cloned());
|
||||
let mut client = AgentDriverClient::spawn(launch).await?;
|
||||
client.try_optional_handshake(manager.agent_app_version()).await;
|
||||
Ok(client)
|
||||
@@ -375,6 +427,21 @@ for line in sys.stdin:
|
||||
assert_ne!(shared_runtime_key("oracle", &base), shared_runtime_key("oracle", &different_args));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_runtime_key_isolates_process_scoped_env() {
|
||||
let base = crate::db::agent_driver::AgentLaunchSpec::new(PathBuf::from("oracle-agent"));
|
||||
let with_nls =
|
||||
base.clone().with_env([("NLS_LANG".to_string(), "SIMPLIFIED CHINESE_CHINA.AL32UTF8".to_string())]);
|
||||
let with_other_nls = base.clone().with_env([("NLS_LANG".to_string(), "AMERICAN_AMERICA.AL32UTF8".to_string())]);
|
||||
|
||||
// Setting a process-scoped variable must route to a dedicated process …
|
||||
assert_ne!(shared_runtime_key("oracle", &base), shared_runtime_key("oracle", &with_nls));
|
||||
// … and two different values must never share one process either.
|
||||
assert_ne!(shared_runtime_key("oracle", &with_nls), shared_runtime_key("oracle", &with_other_nls));
|
||||
// Identical env still reuses the same process.
|
||||
assert_eq!(shared_runtime_key("oracle", &with_nls), shared_runtime_key("oracle", &with_nls.clone()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_open_forgets_runtime_when_no_other_session_uses_it() {
|
||||
let (manager, cell, runtime, script_path) = test_shared_runtime("failed-open-unused").await;
|
||||
|
||||
@@ -461,13 +461,21 @@ pub fn build_agent_list(am: &AgentManager, registry: Option<&AgentRegistry>) ->
|
||||
let local_state = am.load_state();
|
||||
let use_managed_jre = local_state.java_runtime.mode == JavaRuntimeMode::Managed;
|
||||
agent_catalog::driver_store_entries()
|
||||
.map(|(key, label)| {
|
||||
.filter_map(|(key, label)| {
|
||||
let jar_valid = am.is_driver_jar_valid(key);
|
||||
let native_installed = am.driver_native_installed(key);
|
||||
let launch_config_installed = am.driver_launch_config_path(key).exists();
|
||||
let installed = jar_valid || native_installed || launch_config_installed;
|
||||
let local = local_state.installed_drivers.get(key);
|
||||
let remote = registry.and_then(|r| agent_registry_driver(r, key));
|
||||
// A driver the registry publishes nothing for on this platform (the
|
||||
// Windows-only Oracle OCI agent on macOS, for example) cannot be
|
||||
// installed here, and offering it would only produce a download or
|
||||
// JRE fetch that must fail. Already-installed entries stay listed so
|
||||
// they can still be upgraded or uninstalled.
|
||||
if !installed && remote.is_some_and(|driver| !driver_installable_on_current_platform(key, driver)) {
|
||||
return None;
|
||||
}
|
||||
let remote_requires_java_runtime = remote.is_some_and(remote_driver_requires_java_runtime);
|
||||
let requires_java_runtime = if installed {
|
||||
jar_valid && !native_installed && !launch_config_installed
|
||||
@@ -485,7 +493,7 @@ pub fn build_agent_list(am: &AgentManager, registry: Option<&AgentRegistry>) ->
|
||||
&& use_managed_jre
|
||||
&& (!am.is_jre_installed(&jre_key)
|
||||
|| remote_jre_version.is_some_and(|version| local_jre_version != Some(version)));
|
||||
AgentDriverInfo {
|
||||
Some(AgentDriverInfo {
|
||||
db_type: key.to_string(),
|
||||
label: label.to_string(),
|
||||
version: remote.map(|r| r.version.clone()).unwrap_or_default(),
|
||||
@@ -499,7 +507,7 @@ pub fn build_agent_list(am: &AgentManager, registry: Option<&AgentRegistry>) ->
|
||||
requires_java_runtime,
|
||||
jre: jre_key.clone(),
|
||||
jre_installed: !requires_java_runtime || am.is_jre_installed(&jre_key),
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -508,6 +516,19 @@ fn usable_driver_jar(driver: &crate::agent_manager::DriverInfo) -> Option<&crate
|
||||
driver.jar.as_ref().filter(|artifact| artifact.size > 0)
|
||||
}
|
||||
|
||||
/// Whether the registry publishes an artifact this platform can actually run:
|
||||
/// a native agent binary built for it, or the Java JAR fallback.
|
||||
///
|
||||
/// The SQLite SSH worker is the one driver whose binaries execute on the remote
|
||||
/// SSH host instead of the desktop, so a `native` set without an entry for this
|
||||
/// platform is still installable here (#8987).
|
||||
fn driver_installable_on_current_platform(db_type: &str, driver: &crate::agent_manager::DriverInfo) -> bool {
|
||||
if AgentManager::is_sqlite_worker_driver(db_type) {
|
||||
return true;
|
||||
}
|
||||
driver.native.contains_key(AgentManager::current_platform()) || usable_driver_jar(driver).is_some()
|
||||
}
|
||||
|
||||
fn driver_download_artifact(driver: &crate::agent_manager::DriverInfo) -> Option<&crate::agent_manager::ArtifactInfo> {
|
||||
driver.native.get(AgentManager::current_platform()).or_else(|| usable_driver_jar(driver))
|
||||
}
|
||||
@@ -1738,7 +1759,11 @@ async fn install_agent_driver_from_registry(
|
||||
let jre_key = &driver.jre;
|
||||
let native_artifact = driver.native.get(AgentManager::current_platform());
|
||||
let jar_artifact = usable_driver_jar(driver);
|
||||
let requires_java_runtime = native_artifact.is_none();
|
||||
// Java is only required when the JAR fallback is what actually gets
|
||||
// installed. A driver that publishes no artifact for this platform at all
|
||||
// (the Windows-only Oracle OCI agent on macOS, for example) must fail
|
||||
// immediately instead of downloading and unpacking a JRE it cannot use.
|
||||
let requires_java_runtime = native_artifact.is_none() && jar_artifact.is_some();
|
||||
let needs_jre = requires_java_runtime && jre_needs_install(am, registry, jre_key);
|
||||
|
||||
if needs_jre {
|
||||
@@ -4901,6 +4926,45 @@ mod agent_registry_install_tests {
|
||||
assert_eq!(state.jre_versions[DEFAULT_JRE_KEY], jre_version);
|
||||
}
|
||||
|
||||
/// The managed JRE is only needed for the JAR fallback. A driver the registry
|
||||
/// publishes for another platform only — the Windows-only Oracle OCI agent on
|
||||
/// macOS — must fail on the missing artifact instead of fetching and
|
||||
/// unpacking a JRE it can never use.
|
||||
#[tokio::test]
|
||||
async fn ensure_agent_runtime_fails_without_fetching_a_jre_when_no_local_artifact_exists() {
|
||||
let _test_guard = ENSURE_AGENT_TEST_LOCK.lock().await;
|
||||
let manager = test_manager("ensure-no-local-artifact");
|
||||
let db_type = "oracle-oci";
|
||||
let foreign_platform =
|
||||
if AgentManager::current_platform() == "windows-x64" { "linux-x64" } else { "windows-x64" };
|
||||
let mut registry = registry_with_jar(
|
||||
db_type,
|
||||
"0.1.0",
|
||||
"https://example.invalid/dbx-agent-oracle-oci-legacy-placeholder.jar",
|
||||
0,
|
||||
);
|
||||
registry.jres = registry_with_jre(DEFAULT_JRE_KEY, "21.0.12", "https://example.invalid/dbx-jre.tar.gz", 8).jres;
|
||||
registry.drivers.get_mut(db_type).unwrap().native.insert(
|
||||
foreign_platform.to_string(),
|
||||
ArtifactInfo {
|
||||
url: format!("https://example.invalid/dbx-agent-oracle-oci-{foreign_platform}"),
|
||||
sha256: None,
|
||||
size: 8,
|
||||
format: None,
|
||||
},
|
||||
);
|
||||
cache_test_registry(registry).await;
|
||||
|
||||
let error = ensure_agent_driver_ready_from(&manager, db_type, DownloadSource::Cnb).await.unwrap_err();
|
||||
|
||||
assert!(error.contains("No driver artifact available"), "{error}");
|
||||
assert!(
|
||||
!manager.is_jre_installed(DEFAULT_JRE_KEY),
|
||||
"the JRE must not be downloaded for an uninstallable driver"
|
||||
);
|
||||
assert!(!manager.is_driver_installed(db_type));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ensure_agent_runtime_ready_fast_path_preserves_valid_old_driver() {
|
||||
let _test_guard = ENSURE_AGENT_TEST_LOCK.lock().await;
|
||||
|
||||
@@ -15,6 +15,7 @@ pub mod agent_runtime;
|
||||
pub mod agent_service;
|
||||
pub mod backend_error;
|
||||
pub mod database_capabilities;
|
||||
pub mod oracle_oci;
|
||||
|
||||
pub mod db {
|
||||
pub use crate::agent_driver;
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Launch environment for the Oracle OCI ("thick") driver.
|
||||
//!
|
||||
//! The Oracle Client is a process-scoped C library: `NLS_LANG` is read once when
|
||||
//! the client initialises, and the Instant Client shared library is resolved
|
||||
//! through the platform loader path. Neither can be changed after the process
|
||||
//! has started, so a connection that declares either setting must get its own
|
||||
//! agent process.
|
||||
//!
|
||||
//! The entries produced here are folded into
|
||||
//! [`crate::agent_driver::AgentLaunchSpec::env`], which
|
||||
//! [`crate::agent_runtime::shared_runtime_key`] hashes. That is the whole
|
||||
//! isolation mechanism: distinct environments land on distinct runtime keys,
|
||||
//! hence distinct processes, with no extra bookkeeping at the call site.
|
||||
|
||||
/// `driver_profile` value that selects the OCI (thick) driver for Oracle.
|
||||
pub const ORACLE_OCI_DRIVER_PROFILE: &str = "oci";
|
||||
|
||||
/// Client-side character set and territory, read by the Oracle Client on init.
|
||||
pub const NLS_LANG_ENV: &str = "NLS_LANG";
|
||||
|
||||
/// Directory holding `tnsnames.ora` / `sqlnet.ora`.
|
||||
pub const TNS_ADMIN_ENV: &str = "TNS_ADMIN";
|
||||
|
||||
/// Loader path variable the Oracle Client shared library is resolved through.
|
||||
pub fn oracle_client_lib_path_var() -> &'static str {
|
||||
if cfg!(windows) {
|
||||
"PATH"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"DYLD_LIBRARY_PATH"
|
||||
} else {
|
||||
"LD_LIBRARY_PATH"
|
||||
}
|
||||
}
|
||||
|
||||
fn path_separator() -> &'static str {
|
||||
if cfg!(windows) {
|
||||
";"
|
||||
} else {
|
||||
":"
|
||||
}
|
||||
}
|
||||
|
||||
fn trimmed_non_empty(value: Option<&str>) -> Option<&str> {
|
||||
value.map(str::trim).filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
/// Prepends `client_dir` to an existing loader path value.
|
||||
///
|
||||
/// Already-present entries are left alone so repeated resolution cannot grow the
|
||||
/// variable without bound.
|
||||
pub fn prepend_oracle_client_dir(current: Option<&str>, client_dir: &str) -> String {
|
||||
let client_dir = client_dir.trim();
|
||||
let separator = path_separator();
|
||||
match trimmed_non_empty(current) {
|
||||
Some(existing) if !existing.split(separator).any(|entry| entry.trim() == client_dir) => {
|
||||
format!("{client_dir}{separator}{existing}")
|
||||
}
|
||||
Some(existing) => existing.to_string(),
|
||||
None => client_dir.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the agent-process environment for an Oracle OCI connection.
|
||||
///
|
||||
/// Returns an empty vector when nothing is configured, which keeps the launch
|
||||
/// fingerprint identical to a plain Oracle launch so the default process stays
|
||||
/// shared.
|
||||
pub fn oracle_oci_launch_env(
|
||||
nls_lang: Option<&str>,
|
||||
client_dir: Option<&str>,
|
||||
tns_admin: Option<&str>,
|
||||
) -> Vec<(String, String)> {
|
||||
let mut env = Vec::new();
|
||||
if let Some(nls_lang) = trimmed_non_empty(nls_lang) {
|
||||
env.push((NLS_LANG_ENV.to_string(), nls_lang.to_string()));
|
||||
}
|
||||
if let Some(tns_admin) = trimmed_non_empty(tns_admin) {
|
||||
env.push((TNS_ADMIN_ENV.to_string(), tns_admin.to_string()));
|
||||
}
|
||||
if let Some(client_dir) = trimmed_non_empty(client_dir) {
|
||||
let var = oracle_client_lib_path_var();
|
||||
let current = std::env::var(var).ok();
|
||||
env.push((var.to_string(), prepend_oracle_client_dir(current.as_deref(), client_dir)));
|
||||
}
|
||||
env
|
||||
}
|
||||
|
||||
/// JDBC URL prefixes of the two Oracle protocols. The connection dialog always
|
||||
/// stores the thin form; an OCI connection has to launch the same target with
|
||||
/// the `oci8` protocol instead.
|
||||
const ORACLE_THIN_URL_PREFIX: &str = "jdbc:oracle:thin:";
|
||||
const ORACLE_OCI_URL_PREFIX: &str = "jdbc:oracle:oci8:";
|
||||
|
||||
/// Whether `config` selects the OCI (thick) driver.
|
||||
pub fn uses_oracle_oci_profile(config: &crate::models::connection::ConnectionConfig) -> bool {
|
||||
config.driver_profile.as_deref() == Some(ORACLE_OCI_DRIVER_PROFILE)
|
||||
}
|
||||
|
||||
/// Switches an Oracle JDBC URL between the thin and OCI protocol.
|
||||
///
|
||||
/// Unknown shapes are returned trimmed but unchanged, so a hand-written URL
|
||||
/// (connect descriptor, TNS alias, `//host:port/service`) keeps working.
|
||||
pub fn rewrite_oracle_url_protocol(url: &str, oci: bool) -> String {
|
||||
let trimmed = url.trim();
|
||||
let (from, to) = if oci {
|
||||
(ORACLE_THIN_URL_PREFIX, ORACLE_OCI_URL_PREFIX)
|
||||
} else {
|
||||
(ORACLE_OCI_URL_PREFIX, ORACLE_THIN_URL_PREFIX)
|
||||
};
|
||||
if trimmed.len() >= from.len() && trimmed[..from.len()].eq_ignore_ascii_case(from) {
|
||||
return format!("{to}{}", &trimmed[from.len()..]);
|
||||
}
|
||||
trimmed.to_string()
|
||||
}
|
||||
|
||||
/// Drops a query string that only carries `TNS_ADMIN`.
|
||||
///
|
||||
/// OCI reads the directory from the `TNS_ADMIN` environment variable of the
|
||||
/// agent process (see [`oracle_oci_launch_env`]), so the dialog's
|
||||
/// `?TNS_ADMIN=…` suffix is redundant there. Any other parameter is preserved.
|
||||
pub fn strip_oracle_tns_admin_query(url: &str) -> String {
|
||||
let Some((base, query)) = url.split_once('?') else {
|
||||
return url.to_string();
|
||||
};
|
||||
let pairs: Vec<&str> = query.split('&').filter(|pair| !pair.trim().is_empty()).collect();
|
||||
let only_tns_admin = !pairs.is_empty()
|
||||
&& pairs.iter().all(|pair| pair.split('=').next().is_some_and(|key| key.eq_ignore_ascii_case("TNS_ADMIN")));
|
||||
if only_tns_admin {
|
||||
base.to_string()
|
||||
} else {
|
||||
url.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the `TNS_ADMIN` directory the TNS connection form packs into the URL.
|
||||
pub fn oracle_tns_admin_from_connection_string(connection_string: &str) -> Option<String> {
|
||||
let (_, query) = connection_string.trim().split_once('?')?;
|
||||
query.split('&').find_map(|pair| {
|
||||
let (key, value) = pair.split_once('=')?;
|
||||
if !key.eq_ignore_ascii_case("TNS_ADMIN") {
|
||||
return None;
|
||||
}
|
||||
let decoded = percent_decode(value.trim());
|
||||
(!decoded.is_empty()).then_some(decoded)
|
||||
})
|
||||
}
|
||||
|
||||
/// 解析 OCI 连接使用的 `TNS_ADMIN` 目录。
|
||||
///
|
||||
/// 优先级:连接级字段 > TNS 连接串里打包的目录 > 全局默认。连接串里的目录
|
||||
/// 来自 TNS 连接方式(前端把它打包进 JDBC URL),属于本连接自己的配置,
|
||||
/// 因此优先于全局默认。
|
||||
pub fn resolve_oci_tns_admin(
|
||||
explicit: Option<&str>,
|
||||
connection_string: Option<&str>,
|
||||
global_default: Option<&str>,
|
||||
) -> Option<String> {
|
||||
trimmed_non_empty(explicit)
|
||||
.map(str::to_string)
|
||||
.or_else(|| connection_string.and_then(oracle_tns_admin_from_connection_string))
|
||||
.or_else(|| trimmed_non_empty(global_default).map(str::to_string))
|
||||
}
|
||||
|
||||
/// Minimal `application/x-www-form-urlencoded` decoder (`%XX` escapes and `+`).
|
||||
fn percent_decode(value: &str) -> String {
|
||||
let bytes = value.as_bytes();
|
||||
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
match bytes[index] {
|
||||
b'+' => {
|
||||
out.push(b' ');
|
||||
index += 1;
|
||||
}
|
||||
b'%' if index + 3 <= bytes.len() => {
|
||||
let hex = std::str::from_utf8(&bytes[index + 1..index + 3])
|
||||
.ok()
|
||||
.and_then(|hex| u8::from_str_radix(hex, 16).ok());
|
||||
match hex {
|
||||
Some(byte) => {
|
||||
out.push(byte);
|
||||
index += 3;
|
||||
}
|
||||
None => {
|
||||
out.push(bytes[index]);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
byte => {
|
||||
out.push(byte);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unconfigured_oci_launch_shares_the_default_process() {
|
||||
assert!(oracle_oci_launch_env(None, None, None).is_empty());
|
||||
assert!(oracle_oci_launch_env(Some(" "), Some(""), None).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nls_lang_is_process_scoped_environment() {
|
||||
let env = oracle_oci_launch_env(Some(" SIMPLIFIED CHINESE_CHINA.AL32UTF8 "), None, None);
|
||||
assert_eq!(env, vec![(NLS_LANG_ENV.to_string(), "SIMPLIFIED CHINESE_CHINA.AL32UTF8".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tns_admin_is_passed_through() {
|
||||
let env = oracle_oci_launch_env(None, None, Some("/opt/oracle/network/admin"));
|
||||
assert_eq!(env, vec![(TNS_ADMIN_ENV.to_string(), "/opt/oracle/network/admin".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_dir_is_prepended_to_the_loader_path() {
|
||||
let env = oracle_oci_launch_env(None, Some("C:/instantclient_21_12"), None);
|
||||
let var = oracle_client_lib_path_var();
|
||||
assert_eq!(env.len(), 1);
|
||||
assert_eq!(env[0].0, var);
|
||||
assert!(env[0].1.starts_with("C:/instantclient_21_12"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepend_uses_the_platform_separator() {
|
||||
let separator = path_separator();
|
||||
assert_eq!(
|
||||
prepend_oracle_client_dir(Some("/usr/lib"), "/opt/oracle"),
|
||||
format!("/opt/oracle{separator}/usr/lib")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepend_is_idempotent() {
|
||||
let once = prepend_oracle_client_dir(Some("/usr/lib"), "/opt/oracle");
|
||||
assert_eq!(prepend_oracle_client_dir(Some(&once), "/opt/oracle"), once);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepend_without_current_value_returns_client_dir() {
|
||||
assert_eq!(prepend_oracle_client_dir(None, "/opt/oracle"), "/opt/oracle");
|
||||
assert_eq!(prepend_oracle_client_dir(Some(" "), "/opt/oracle"), "/opt/oracle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oci_profile_matches_the_connection_type_declaration() {
|
||||
assert_eq!(ORACLE_OCI_DRIVER_PROFILE, "oci");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thin_urls_are_rewritten_to_the_oci_protocol() {
|
||||
assert_eq!(
|
||||
rewrite_oracle_url_protocol("jdbc:oracle:thin:@//db.example.com:1521/ORCLPDB1", true),
|
||||
"jdbc:oracle:oci8:@//db.example.com:1521/ORCLPDB1"
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_oracle_url_protocol("jdbc:oracle:thin:@db.example.com:1521:ORCL", true),
|
||||
"jdbc:oracle:oci8:@db.example.com:1521:ORCL"
|
||||
);
|
||||
assert_eq!(
|
||||
rewrite_oracle_url_protocol(
|
||||
"jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=h)(PORT=1521)))",
|
||||
true
|
||||
),
|
||||
"jdbc:oracle:oci8:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=h)(PORT=1521)))"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oci_urls_are_rewritten_back_to_thin() {
|
||||
assert_eq!(
|
||||
rewrite_oracle_url_protocol("jdbc:oracle:oci8:@//db.example.com:1521/ORCLPDB1", false),
|
||||
"jdbc:oracle:thin:@//db.example.com:1521/ORCLPDB1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_url_shapes_are_left_alone() {
|
||||
assert_eq!(rewrite_oracle_url_protocol("jdbc:postgresql://db/app", true), "jdbc:postgresql://db/app");
|
||||
assert_eq!(rewrite_oracle_url_protocol("", true), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tns_admin_prefers_the_connection_field_over_the_url_and_global() {
|
||||
assert_eq!(
|
||||
resolve_oci_tns_admin(
|
||||
Some("C:/wallets/adb"),
|
||||
Some("jdbc:oracle:oci8:@ALIAS?TNS_ADMIN=C:/from-url"),
|
||||
Some("C:/global"),
|
||||
)
|
||||
.as_deref(),
|
||||
Some("C:/wallets/adb")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tns_admin_falls_back_to_the_url_then_the_global_default() {
|
||||
assert_eq!(
|
||||
resolve_oci_tns_admin(None, Some("jdbc:oracle:oci8:@ALIAS?TNS_ADMIN=C:/from-url"), Some("C:/global"),)
|
||||
.as_deref(),
|
||||
Some("C:/from-url")
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_oci_tns_admin(None, Some("jdbc:oracle:oci8:@ALIAS"), Some("C:/global")).as_deref(),
|
||||
Some("C:/global")
|
||||
);
|
||||
assert_eq!(resolve_oci_tns_admin(None, None, None), None);
|
||||
assert_eq!(resolve_oci_tns_admin(Some(" "), None, Some("C:/global")).as_deref(), Some("C:/global"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tns_admin_query_is_read_and_decoded() {
|
||||
assert_eq!(
|
||||
oracle_tns_admin_from_connection_string(
|
||||
"jdbc:oracle:thin:@ORCLPDB1?TNS_ADMIN=C%3A%5Coracle%5Cnetwork%5Cadmin"
|
||||
),
|
||||
Some("C:\\oracle\\network\\admin".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
oracle_tns_admin_from_connection_string("jdbc:oracle:thin:@ORCLPDB1?TNS_ADMIN=/opt/oracle/admin"),
|
||||
Some("/opt/oracle/admin".to_string())
|
||||
);
|
||||
assert_eq!(oracle_tns_admin_from_connection_string("jdbc:oracle:thin:@//host:1521/svc"), None);
|
||||
assert_eq!(oracle_tns_admin_from_connection_string(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tns_admin_query_is_stripped_only_when_it_stands_alone() {
|
||||
assert_eq!(
|
||||
strip_oracle_tns_admin_query("jdbc:oracle:oci8:@ORCLPDB1?TNS_ADMIN=/opt/oracle/admin"),
|
||||
"jdbc:oracle:oci8:@ORCLPDB1"
|
||||
);
|
||||
assert_eq!(
|
||||
strip_oracle_tns_admin_query("jdbc:oracle:oci8:@ORCLPDB1?TNS_ADMIN=/opt/oracle/admin&other=1"),
|
||||
"jdbc:oracle:oci8:@ORCLPDB1?TNS_ADMIN=/opt/oracle/admin&other=1"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7554,6 +7554,8 @@ mod tests {
|
||||
|
||||
fn redis_test_connection_config() -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "redis".to_string(),
|
||||
name: "Redis".to_string(),
|
||||
|
||||
@@ -11,7 +11,7 @@ pub use dbx_types::{database_manifest, models, types};
|
||||
|
||||
pub use dbx_driver_agent::{
|
||||
agent_catalog, agent_connection, agent_manager, agent_offline_export, agent_recovery, agent_runtime, agent_service,
|
||||
backend_error, database_capabilities,
|
||||
backend_error, database_capabilities, oracle_oci,
|
||||
};
|
||||
pub mod db;
|
||||
pub use dbx_driver_support::execution;
|
||||
|
||||
@@ -189,6 +189,21 @@ pub struct ConnectionConfig {
|
||||
pub sysdba: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub oracle_connection_type: Option<String>,
|
||||
/// Connection-level NLS_LANG override for OCI connections. Empty keeps the
|
||||
/// global default; a value makes this connection own a dedicated agent
|
||||
/// process so its client charset cannot bleed into other sessions (the
|
||||
/// variable is process-scoped for OCI).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub oracle_oci_nls_lang: Option<String>,
|
||||
/// Connection-level `TNS_ADMIN` override for OCI (thick) connections.
|
||||
///
|
||||
/// Points at the directory holding `tnsnames.ora` / `sqlnet.ora` / the
|
||||
/// wallet, so any OCI connection can use an ADB wallet or network options
|
||||
/// without switching to the TNS connection form. Resolved against the
|
||||
/// global default and the TNS connection string in
|
||||
/// `dbx_core::connection::AppState::agent_launch_env`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub oracle_oci_tns_admin: Option<String>,
|
||||
#[serde(default)]
|
||||
pub connection_string: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -645,6 +660,10 @@ struct ConnectionConfigData {
|
||||
#[serde(default)]
|
||||
pub oracle_connection_type: Option<String>,
|
||||
#[serde(default)]
|
||||
pub oracle_oci_nls_lang: Option<String>,
|
||||
#[serde(default)]
|
||||
pub oracle_oci_tns_admin: Option<String>,
|
||||
#[serde(default)]
|
||||
pub connection_string: Option<String>,
|
||||
#[serde(default)]
|
||||
pub redis_connection_mode: Option<String>,
|
||||
@@ -741,6 +760,8 @@ impl From<ConnectionConfigData> for ConnectionConfig {
|
||||
client_key_path: data.client_key_path,
|
||||
sysdba: data.sysdba,
|
||||
oracle_connection_type: data.oracle_connection_type,
|
||||
oracle_oci_nls_lang: data.oracle_oci_nls_lang,
|
||||
oracle_oci_tns_admin: data.oracle_oci_tns_admin,
|
||||
connection_string: data.connection_string,
|
||||
redis_connection_mode: data.redis_connection_mode,
|
||||
redis_sentinel_master: data.redis_sentinel_master,
|
||||
@@ -2823,6 +2844,8 @@ mod tests {
|
||||
|
||||
fn mysql_config(username: &str, password: &str, database: Option<&str>) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: "id".to_string(),
|
||||
name: "name".to_string(),
|
||||
|
||||
@@ -1050,6 +1050,8 @@ mod tests {
|
||||
|
||||
fn sqlite_config(id: &str, path: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: "SQLite".to_string(),
|
||||
|
||||
@@ -239,6 +239,8 @@ mod tests {
|
||||
client_key_path: String::new(),
|
||||
sysdba: false,
|
||||
oracle_connection_type: None,
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
connection_string: None,
|
||||
redis_connection_mode: None,
|
||||
redis_sentinel_master: String::new(),
|
||||
|
||||
@@ -679,6 +679,8 @@ mod tests {
|
||||
|
||||
fn sqlite_config(id: &str, path: &str) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
oracle_oci_nls_lang: None,
|
||||
oracle_oci_tns_admin: None,
|
||||
docs_notes_path: None,
|
||||
id: id.to_string(),
|
||||
name: "SQLite".to_string(),
|
||||
|
||||
Reference in new issue
Block a user