diff --git a/Cargo.lock b/Cargo.lock index 0a107baed..308c37ff9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4319,6 +4319,7 @@ dependencies = [ "futures", "ide-core", "ide-http", + "ide-sdk", "ide-ssh", "notify", "open", @@ -4340,6 +4341,7 @@ dependencies = [ "tracing", "uuid", "zeroize", + "zip", ] [[package]] diff --git a/crates/ide-db/Cargo.toml b/crates/ide-db/Cargo.toml index 7f14eb86a..5c2d90c9c 100644 --- a/crates/ide-db/Cargo.toml +++ b/crates/ide-db/Cargo.toml @@ -7,6 +7,9 @@ license.workspace = true [dependencies] ide-core.workspace = true +ide-sdk.workspace = true +tempfile.workspace = true +zip.workspace = true dunce.workspace = true serde.workspace = true serde_json = { workspace = true, features = ["raw_value"] } @@ -38,5 +41,4 @@ open = "5" [dev-dependencies] tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net"] } -tempfile.workspace = true ide-ssh = { workspace = true, features = ["testing"] } diff --git a/crates/ide-db/src/conn.rs b/crates/ide-db/src/conn.rs index 266cf53c9..078b14b6b 100644 --- a/crates/ide-db/src/conn.rs +++ b/crates/ide-db/src/conn.rs @@ -237,6 +237,7 @@ pub enum Pool { Mysql(ServerPool), SqlServer(Bb8Pool), Clickhouse(crate::clickhouse::ClickhousePool), + Jdbc(Box), Oracle(crate::oracle::OraclePool), Snowflake(crate::snowflake::SnowflakePool), } @@ -729,6 +730,7 @@ impl Pool { Pool::Mysql(_) => DbDriver::Mysql, Pool::SqlServer(_) => DbDriver::SqlServer, Pool::Clickhouse(_) => DbDriver::Clickhouse, + Pool::Jdbc(_) => DbDriver::Jdbc, Pool::Oracle(_) => DbDriver::Oracle, Pool::Snowflake(_) => DbDriver::Snowflake, } @@ -919,6 +921,7 @@ impl Pool { conn.query("SELECT 1", &[]).await.map_err(mssql_err)?.into_results().await.map_err(mssql_err)?; Ok(Pool::SqlServer(pool)) } + DbDriver::Jdbc => Err(IdeError::invalid("An installed JDBC driver profile is required")), DbDriver::Clickhouse => unreachable!(), DbDriver::Oracle | DbDriver::Snowflake => unreachable!(), } @@ -928,6 +931,7 @@ impl Pool { match self { Pool::SqlServer(_) | Pool::Oracle(_) => {} Pool::Clickhouse(p) => p.close(), + Pool::Jdbc(p) => p.close().await, Pool::Snowflake(p) => p.close().await, Pool::Sqlite(p) => p.close().await, Pool::Postgres(p) => p.closed.store(true, Ordering::Relaxed), @@ -940,6 +944,7 @@ impl Pool { Pool::SqlServer(_) => false, Pool::Oracle(p) => p.is_closed(), Pool::Clickhouse(p) => p.is_closed(), + Pool::Jdbc(p) => p.is_closed(), Pool::Snowflake(p) => p.is_closed(), Pool::Sqlite(p) => p.is_closed(), Pool::Postgres(p) => p.closed.load(Ordering::Relaxed), @@ -949,6 +954,9 @@ impl Pool { /// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]). pub async fn rows(&self, sql: &str, max: usize) -> IdeResult>>> { + if let Pool::Jdbc(p) = self { + return Ok(p.query(sql, 0, max, &CancellationToken::new()).await?.rows); + } if let Pool::Clickhouse(p) = self { return Ok(p.execute(sql, max, &CancellationToken::new()).await?.rows); } @@ -976,6 +984,9 @@ impl Pool { max_rows: usize, cancel: &CancellationToken, ) -> IdeResult { + if let Pool::Jdbc(p) = self { + return p.query(sql, skip, max_rows, cancel).await; + } if let Pool::Clickhouse(p) = self { return p.execute_from(sql, skip, max_rows, cancel).await; } @@ -998,6 +1009,7 @@ impl Pool { /// row when flagged (table editor submits). pub async fn transaction(&self, statements: &[(String, bool)]) -> IdeResult { match self { + Pool::Jdbc(_) => Err(IdeError::invalid("Custom JDBC table editing is unsupported")), Pool::Clickhouse(_) => Err(crate::clickhouse::transaction_error()), Pool::Snowflake(p) => p.transaction(statements).await, Pool::SqlServer(_) => { @@ -1088,6 +1100,7 @@ pub enum Held { impl Held { pub async fn acquire(pool: &Pool) -> IdeResult { Ok(match pool { + Pool::Jdbc(_) => return Err(IdeError::invalid("Custom JDBC manual transactions are unsupported")), Pool::Sqlite(p) => Held::Sqlite(p.acquire().await.map_err(db_err)?), Pool::Postgres(p) => Held::Postgres(Box::new(p.get().await?)), Pool::Mysql(p) => Held::Mysql(Box::new(p.get().await?)), @@ -1377,7 +1390,7 @@ pub fn begin_statement(driver: DbDriver) -> &'static str { DbDriver::Mysql => "START TRANSACTION", DbDriver::SqlServer => "BEGIN TRAN", DbDriver::Oracle => "", // opens implicitly with autocommit off - DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Clickhouse | DbDriver::Snowflake => "BEGIN", + DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Clickhouse | DbDriver::Snowflake | DbDriver::Jdbc => "BEGIN", } } diff --git a/crates/ide-db/src/jdbc/mod.rs b/crates/ide-db/src/jdbc/mod.rs new file mode 100644 index 000000000..4ed2d8d6d --- /dev/null +++ b/crates/ide-db/src/jdbc/mod.rs @@ -0,0 +1,678 @@ +//! A trusted local driver profile is shared by data sources. JDBC URLs and properties +//! can run driver-specific initialization. A project source may connect only with the +//! settings its user last accepted in the dialog; the approval lives outside the project. +use crate::{DataSource, DbManager, QueryResult, ResultColumn}; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::io::{Cursor, Read}; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::time::{Duration, Instant}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::process::{ChildStdin, ChildStdout, Command}; +use tokio::sync::Mutex; +use tokio::time::{Instant as Deadline, timeout_at}; + +const LIMIT: usize = 16 * 1024 * 1024; + +#[derive(Debug, Clone, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DbJdbcDriver { + pub id: String, + pub name: String, + pub jars: Vec, + pub class_name: String, + pub url_template: String, +} + +fn persist_local(path: &Path, data: &[u8]) -> IdeResult<()> { + let dir = path.parent().expect("registry paths have a parent"); + std::fs::create_dir_all(dir)?; + let mut tmp = tempfile::NamedTempFile::new_in(dir)?; + std::io::Write::write_all(&mut tmp, data)?; + tmp.persist(path).map_err(|e| IdeError::from(e.error))?; + Ok(()) +} + +fn local_jar(jar: &str) -> IdeResult<&Path> { + if jar.contains(if cfg!(windows) { ';' } else { ':' }) { + return Err(IdeError::invalid("A JDBC JAR path contains the system classpath separator")); + } + let path = Path::new(jar); + if !path.is_absolute() || !path.is_file() || !path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("jar")) { + return Err(IdeError::invalid("Choose an existing local .jar file for each JDBC driver file")); + } + Ok(path) +} + +/// Read the standard JDBC service descriptors without executing any driver code. +pub fn jdbc_driver_classes(jars: &[String]) -> IdeResult> { + let mut classes = Vec::new(); + if jars.len() > 128 { + return Err(IdeError::invalid("Choose at most 128 JDBC driver files")); + } + for jar in jars { + let file = std::fs::File::open(local_jar(jar)?)?; + let mut archive = zip::ZipArchive::new(file).map_err(|_| IdeError::invalid("Invalid JDBC JAR archive"))?; + let descriptor = match archive.by_name("META-INF/services/java.sql.Driver") { + Ok(entry) => entry, + Err(zip::result::ZipError::FileNotFound) => continue, + Err(_) => return Err(IdeError::invalid("Cannot read the JDBC driver descriptor")), + }; + let mut text = String::new(); + descriptor.take(65537).read_to_string(&mut text)?; + if text.len() > 65536 { + return Err(IdeError::invalid("JDBC driver descriptor is too large")); + } + for line in text.lines() { + let name = line.split('#').next().unwrap_or_default().trim(); + if !name.is_empty() + && name.split('.').all(|part| { + let mut chars = part.chars(); + chars.next().is_some_and(|c| c.is_alphabetic() || matches!(c, '_' | '$')) + && chars.all(|c| c.is_alphanumeric() || matches!(c, '_' | '$')) + }) + && !classes.iter().any(|s| s == name) + { + classes.push(name.to_owned()); + } + } + } + Ok(classes) +} + +impl DbJdbcDriver { + fn validate(&self) -> IdeResult<()> { + if self.id.is_empty() + || self.name.trim().is_empty() + || self.jars.is_empty() + || self.class_name.trim().is_empty() + { + return Err(IdeError::invalid("A JDBC driver needs a name, a driver class and at least one JAR")); + } + if !self.url_template.is_empty() && !self.url_template.starts_with("jdbc:") { + return Err(IdeError::invalid("The JDBC URL template must start with jdbc:")); + } + for jar in &self.jars { + local_jar(jar)?; + } + Ok(()) + } +} + +impl DbManager { + fn jdbc_registry(&self) -> IdeResult { + self.global + .as_ref() + .map(|(dir, _)| dir.join("jdbc-drivers.json")) + .ok_or_else(|| IdeError::invalid("Global JDBC driver profiles are unavailable here")) + } + + pub fn jdbc_drivers(&self) -> IdeResult> { + let path = self.jdbc_registry()?; + match std::fs::File::open(path) { + Ok(file) => { + serde_json::from_reader(file).map_err(|e| IdeError::invalid(format!("JDBC driver profiles: {e}"))) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(vec![]), + Err(e) => Err(e.into()), + } + } + + fn update_jdbc_driver(&self, id: &str, driver: Option) -> IdeResult<()> { + let _guard = crate::plugin::EDIT.lock(); + let path = self.jdbc_registry()?; + let mut list = self.jdbc_drivers()?; + list.retain(|d| d.id != id); + list.extend(driver); + let data = serde_json::to_vec_pretty(&list).map_err(|e| IdeError::internal(e.to_string()))?; + persist_local(&path, &data) + } + + pub fn save_jdbc_driver(&self, driver: DbJdbcDriver) -> IdeResult<()> { + driver.validate()?; + self.update_jdbc_driver(&driver.id.clone(), Some(driver)) + } + + pub fn remove_jdbc_driver(&self, id: &str) -> IdeResult<()> { + if self.global_sources().iter().any(|s| s.driver == crate::DbDriver::Jdbc && s.jdbc_driver == id) { + return Err(IdeError::invalid("This JDBC driver is in use by a data source")); + } + self.update_jdbc_driver(id, None) + } + + fn jdbc_approval(&self, source: &DataSource) -> IdeResult<(PathBuf, String)> { + let registry = self.jdbc_registry()?; + let key = serde_json::to_vec(&(&self.root, &source.id)).map_err(|e| IdeError::internal(e.to_string()))?; + let settings = serde_json::to_vec(&( + &source.jdbc_driver, + &source.url, + &source.user, + source.read_only, + &source.properties, + &source.options, + )) + .map_err(|e| IdeError::internal(e.to_string()))?; + Ok(( + registry.with_file_name("jdbc-approvals").join(blake3::hash(&key).to_hex().as_str()), + blake3::hash(&settings).to_hex().to_string(), + )) + } + + /// Called only for the source the user explicitly saved in the connection dialog. + pub fn approve_jdbc_source(&self, source: &DataSource) -> IdeResult<()> { + if source.driver != crate::DbDriver::Jdbc || source.plugin_owner.is_some() { + return Err(IdeError::invalid("Expected a user-managed JDBC data source")); + } + let (path, fingerprint) = self.jdbc_approval(source)?; + persist_local(&path, fingerprint.as_bytes()) + } + + pub(crate) async fn open_pool( + &self, + source: &DataSource, + password: Option<&str>, + testing: bool, + ) -> IdeResult { + if source.driver != crate::DbDriver::Jdbc { + return crate::Pool::connect(source, password, Some(&self.root)).await; + } + if source.plugin_owner.is_some() { + return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers")); + } + if !testing && !source.global { + let (path, expected) = self.jdbc_approval(source)?; + if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) { + return Err(IdeError::invalid( + "Review this project's JDBC URL and properties, then save the data source before connecting", + )); + } + } + let driver = self + .jdbc_drivers()? + .into_iter() + .find(|d| d.id == source.jdbc_driver) + .ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))?; + JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc")) + .await + .map(Box::new) + .map(crate::Pool::Jdbc) + } +} + +struct Bridge { + stop: tokio::sync::oneshot::Sender<()>, + exited: tokio::task::JoinHandle<()>, + sequence: u64, + input: ChildStdin, + output: ChildStdout, +} + +pub struct JdbcPool { + bridge: Mutex>, + closed: CancellationToken, + pub(crate) version: String, + pub(crate) identifier_quote: String, +} + +impl Bridge { + fn start(cache: &Path, jars: &[String]) -> IdeResult { + let jdks = ide_sdk::java::installed_jdks(); + let java = ide_sdk::java::java_runtime(&jdks, 17) + .ok_or_else(|| IdeError::invalid("Install a Java 17 or newer runtime to use custom JDBC drivers"))?; + let jar = ide_sdk::java::jdbc_bridge_jar(cache) + .ok_or_else(|| IdeError::invalid("Cannot install the JDBC bridge in the application data directory"))?; + let classpath = std::env::join_paths(std::iter::once(jar.as_path()).chain(jars.iter().map(Path::new))) + .map_err(|_| IdeError::invalid("A JDBC JAR path contains the system classpath separator"))?; + // Embedded databases can resolve file URLs against the JVM's working directory. + let files = cache.join("files"); + std::fs::create_dir_all(&files)?; + let mut command = Command::new(ide_sdk::java::java_executable(&java.home)); + command.current_dir(files); + ide_core::process::prepare(command.as_std_mut()); + let mut child = command + .args(["-Xms8m", "-Xmx192m", "--enable-native-access=ALL-UNNAMED", "-cp"]) + .arg(classpath) + .arg("ai.openidea.jdbc.OpenIdeaJdbc") + .env_remove("CLASSPATH") + .env_remove("JDK_JAVA_OPTIONS") + .env_remove("JAVA_TOOL_OPTIONS") + .env_remove("_JAVA_OPTIONS") + .kill_on_drop(true) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn()?; + let input = child.stdin.take().expect("piped"); + let output = child.stdout.take().expect("piped"); + let (stop, stopped) = tokio::sync::oneshot::channel(); + let exited = tokio::spawn(async move { + tokio::select! { + stop = stopped => { + // Disconnect closes stdin so a file-backed driver can flush. A dropped + // request or an unresponsive driver must be reaped without waiting. + if stop.is_err() || tokio::time::timeout(Duration::from_secs(2), child.wait()).await.is_err() { + let _ = child.kill().await; + } + } + _ = child.wait() => {} + } + }); + Ok(Self { input, output, stop, exited, sequence: 0 }) + } + + async fn close(self) { + drop(self.input); + let _ = self.stop.send(()); + let _ = self.exited.await; + } +} + +// Request: u64 request id, u32 field count, then length-prefixed UTF-8 fields. +// Zero fields cancels that id. Replies have a u32 length; zero acknowledges Cancel. +fn encode(id: u64, fields: &[&str]) -> IdeResult> { + if fields.is_empty() || fields.len() > 8192 { + return Err(IdeError::invalid("Invalid JDBC field count")); + } + let size = fields + .iter() + .try_fold(12usize, |n, s| n.checked_add(4)?.checked_add(s.len()).filter(|n| *n <= LIMIT)) + .ok_or_else(|| IdeError::invalid("JDBC request exceeds 16 MiB"))?; + let mut data = Vec::with_capacity(size); + data.extend_from_slice(&id.to_be_bytes()); + data.extend_from_slice(&(fields.len() as u32).to_be_bytes()); + for field in fields { + data.extend_from_slice(&(field.len() as u32).to_be_bytes()); + data.extend_from_slice(field.as_bytes()); + } + Ok(data) +} + +async fn read_frame(output: &mut (impl AsyncRead + Unpin)) -> IdeResult> { + let n = output.read_u32().await? as usize; + if n > LIMIT { + return Err(IdeError::invalid("JDBC response exceeds 16 MiB")); + } + let mut data = vec![0; n]; + output.read_exact(&mut data).await?; + Ok(data) +} + +const CANCEL_GRACE: Duration = Duration::from_secs(3); + +fn cancel_timeout() -> IdeError { + IdeError::invalid("The JDBC driver did not stop in time. The session was closed. Reconnect to continue.") +} + +async fn exchange( + input: &mut (impl AsyncWrite + Unpin), + output: &mut (impl AsyncRead + Unpin), + frame: Vec, + cancel: &CancellationToken, +) -> IdeResult>> { + let mut stop = [0; 12]; + stop[..8].copy_from_slice(&frame[..8]); + let early_deadline = { + let send = input.write_all(&frame); + tokio::pin!(send); + tokio::select! { + result = &mut send => { result?; None }, + () = cancel.cancelled() => { + let end = Deadline::now() + CANCEL_GRACE; + timeout_at(end, send).await.map_err(|_| cancel_timeout())??; + Some(end) + } + } + }; + drop(frame); + let (first, deadline) = { + let reply = read_frame(output); + tokio::pin!(reply); + let end = tokio::select! { + biased; + () = cancel.cancelled() => early_deadline.unwrap_or_else(|| Deadline::now() + CANCEL_GRACE), + data = &mut reply => { + let data = data?; + if data.is_empty() { return Err(IdeError::invalid("Unexpected JDBC cancellation acknowledgement")); } + return Ok(Some(data)); + } + }; + let first = timeout_at(end, async { + input.write_all(&stop).await?; + reply.await + }) + .await + .map_err(|_| cancel_timeout())??; + (first, end) + }; + // Drain both frames before the next statement can use this session. The driver + // may complete the statement before or after the control thread acknowledges it. + let data = if first.is_empty() { + timeout_at(deadline, read_frame(output)).await.map_err(|_| cancel_timeout())?? + } else { + if timeout_at(deadline, output.read_u32()).await.map_err(|_| cancel_timeout())?? != 0 { + return Err(IdeError::invalid("Invalid JDBC cancellation acknowledgement")); + } + first + }; + match data.first() { + // A committed statement may have finished before the control thread received Cancel. + Some(1) => Ok(Some(data)), + Some(0) => Ok(None), + _ => Err(IdeError::invalid("Invalid JDBC cancellation response")), + } +} + +impl JdbcPool { + async fn connect( + source: &DataSource, + password: Option<&str>, + driver: DbJdbcDriver, + cache: PathBuf, + ) -> IdeResult { + driver.validate()?; + let mut fields = vec![ + "open".to_string(), + driver.class_name, + source.url.clone(), + source.user.clone(), + password.unwrap_or_default().to_owned(), + source.read_only.to_string(), + ]; + for p in &source.properties { + if p.name.eq_ignore_ascii_case("password") { + return Err(IdeError::invalid("Enter the JDBC password in the password field")); + } + fields.extend([p.name.clone(), p.value.clone()]); + } + let bridge = tokio::task::spawn_blocking(move || Bridge::start(&cache, &driver.jars)) + .await + .map_err(|e| IdeError::internal(e.to_string()))??; + let mut pool = Self { + bridge: Mutex::new(Some(bridge)), + closed: CancellationToken::new(), + version: String::new(), + identifier_quote: String::new(), + }; + let args: Vec<_> = fields.iter().map(String::as_str).collect(); + let cancel = CancellationToken::new(); + let result = tokio::time::timeout(Duration::from_secs(30), pool.request(&args, "", &cancel)) + .await + .map_err(|_| IdeError::new(ide_core::error::ErrorKind::TimedOut, "JDBC connection timed out"))??; + let mut metadata = result.rows.into_iter().next().unwrap_or_default().into_iter(); + pool.version = metadata.next().flatten().unwrap_or_else(|| "Connected".into()); + pool.identifier_quote = metadata.next().flatten().unwrap_or_default().trim().into(); + Ok(pool) + } + + pub(crate) async fn close(&self) { + self.closed.cancel(); + if let Some(bridge) = self.bridge.lock().await.take() { + bridge.close().await; + } + } + + pub(crate) fn is_closed(&self) -> bool { + self.closed.is_cancelled() + } + + pub(crate) async fn query( + &self, + sql: &str, + skip: usize, + max: usize, + cancel: &CancellationToken, + ) -> IdeResult { + self.query_in_schema(sql, skip, max, cancel, None).await + } + + pub(crate) async fn query_in_schema( + &self, + sql: &str, + skip: usize, + max: usize, + cancel: &CancellationToken, + schema: Option<&str>, + ) -> IdeResult { + self.request( + &["query", sql, &skip.to_string(), &max.min(i32::MAX as usize).to_string(), schema.unwrap_or_default()], + sql, + cancel, + ) + .await + } + + pub(crate) async fn page( + &self, + sql: &str, + offset: u64, + limit: u64, + cancel: &CancellationToken, + ) -> IdeResult { + self.request(&["page", sql, &offset.to_string(), &limit.min(i32::MAX as u64).to_string()], sql, cancel).await + } + + pub(crate) async fn metadata(&self, fields: &[&str]) -> IdeResult>>> { + Ok(self.request(fields, "", &CancellationToken::new()).await?.rows) + } + + async fn request(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult { + let mut slot = tokio::select! { + biased; + () = cancel.cancelled() => return Err(IdeError::cancelled()), + () = self.closed.cancelled() => return Err(IdeError::invalid("JDBC connection is closed")), + slot = self.bridge.lock() => slot, + }; + let bridge = slot + .as_mut() + .ok_or_else(|| IdeError::invalid("JDBC connection is closed; reconnect to start a new session"))?; + bridge.sequence = bridge.sequence.wrapping_add(1); + let frame = encode(bridge.sequence, fields)?; + let mut bridge = slot.take().expect("checked above"); + // Dropping an in-flight request must discard its process and partially consumed frame. + let interrupted = self.closed.clone().drop_guard(); + let start = Instant::now(); + let response = tokio::select! { + biased; + () = self.closed.cancelled() => Err(IdeError::cancelled()), + response = exchange(&mut bridge.input, &mut bridge.output, frame, cancel) => response, + }; + let data = match response { + Ok(data) => { + *slot = Some(bridge); + interrupted.disarm(); + data + } + Err(e) => { + drop(bridge.stop); + let _ = bridge.exited.await; + return Err(e); + } + }; + decode(&data.ok_or_else(IdeError::cancelled)?, sql, start.elapsed().as_secs_f64() * 1000.0) + } +} + +fn decode(data: &[u8], sql: &str, elapsed_ms: f64) -> IdeResult { + let mut input = Cursor::new(data); + fn bytes(input: &mut Cursor<&[u8]>) -> IdeResult<[u8; N]> { + let mut buf = [0; N]; + Read::read_exact(input, &mut buf)?; + Ok(buf) + } + fn flag(input: &mut Cursor<&[u8]>) -> IdeResult { + match bytes::<1>(input)? { + [0] => Ok(false), + [1] => Ok(true), + _ => Err(IdeError::invalid("Invalid JDBC flag")), + } + } + fn field(input: &mut Cursor<&[u8]>) -> IdeResult> { + let n = i32::from_be_bytes(bytes(input)?); + if n == -1 { + return Ok(None); + } + let start = input.position() as usize; + let end = start + .checked_add(n as usize) + .filter(|end| *end <= input.get_ref().len()) + .ok_or_else(|| IdeError::invalid("Invalid JDBC field length"))?; + let value = String::from_utf8_lossy(&input.get_ref()[start..end]).into_owned(); + input.set_position(end as u64); + Ok(Some(value)) + } + if !flag(&mut input)? { + return Err(IdeError::invalid(field(&mut input)?.unwrap_or_else(|| "JDBC request failed".into()))); + } + let count = u32::from_be_bytes(bytes(&mut input)?) as usize; + if count > data.len() / 8 { + return Err(IdeError::invalid("Invalid JDBC column count")); + } + let mut columns = Vec::new(); + for _ in 0..count { + columns.push(ResultColumn { + name: field(&mut input)?.unwrap_or_default(), + type_name: field(&mut input)?.unwrap_or_default(), + }); + } + let mut rows = vec![]; + while flag(&mut input)? { + if count == 0 { + return Err(IdeError::invalid("JDBC returned a row with no columns")); + } + rows.push((0..count).map(|_| field(&mut input)).collect::>()?); + } + let has_more = flag(&mut input)?; + let affected = i64::from_be_bytes(bytes(&mut input)?); + if input.position() != data.len() as u64 { + return Err(IdeError::invalid("Invalid trailing JDBC response data")); + } + Ok(QueryResult { + statement: sql.into(), + columns, + rows, + has_more, + affected: (affected >= 0).then_some(affected as f64), + elapsed_ms, + execution_ms: elapsed_ms, + }) +} + +impl DbManager { + pub(crate) async fn jdbc_completion(&self, id: &str, pool: &JdbcPool) -> IdeResult { + let mut tables = vec![]; + let schemas = self.schemas(id).await?; + for schema in &schemas { + for table in self.tables(id, schema).await? { + tables.push(crate::CompletionTable { + schema: schema.clone(), + name: table.name, + kind: table.kind, + columns: vec![], + }); + if tables.len() >= crate::MAX_META_ROWS { + break; + } + } + if tables.len() >= crate::MAX_META_ROWS { + break; + } + } + Ok(crate::CompletionModel { + default_schema: pool + .metadata(&["namespace"]) + .await? + .into_iter() + .flatten() + .flatten() + .next() + .unwrap_or_default(), + tables, + foreign_keys: vec![], + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn frame_codec_checks_both_16_mib_boundaries() { + assert_eq!(encode(7, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 1, b'a']); + let mut field = "x".repeat(LIMIT - 16); + assert_eq!(encode(1, &[&field]).unwrap().len(), LIMIT); + field.push('x'); + assert!(encode(1, &[&field]).is_err()); + let mut framed = vec![0u8; LIMIT + 4]; + framed[..4].copy_from_slice(&(LIMIT as u32).to_be_bytes()); + assert_eq!(read_frame(&mut framed.as_slice()).await.unwrap().len(), LIMIT); + assert!(read_frame(&mut &((LIMIT + 1) as u32).to_be_bytes()[..]).await.is_err()); + assert!(read_frame(&mut &[0, 0, 0, 2, 1u8][..]).await.is_err()); + } + + #[tokio::test] + async fn cancel_drains_partial_replies_in_either_order() { + for ack_first in [true, false] { + let (mut input, mut peer_input) = tokio::io::duplex(1); + let (mut output, mut peer_output) = tokio::io::duplex(1); + let cancel = CancellationToken::new(); + let frame = encode(42, &["query"]).unwrap(); + let peer = async { + let mut request = vec![0; frame.len()]; + peer_input.read_exact(&mut request).await.unwrap(); + assert_eq!(request, frame); + // The one-byte pipe forces the reader to consume part of the header before Cancel. + peer_output.write_all(&[0, 0]).await.unwrap(); + cancel.cancel(); + let mut stop = [0; 12]; + peer_input.read_exact(&mut stop).await.unwrap(); + assert_eq!(&stop[..8], &42u64.to_be_bytes()); + assert_eq!(&stop[8..], &[0; 4]); + let frames = if ack_first { [0, 0, 0, 0, 0, 1, 0] } else { [0, 1, 1, 0, 0, 0, 0] }; + peer_output.write_all(&frames).await.unwrap(); + }; + let (result, ()) = tokio::join!(exchange(&mut input, &mut output, frame.clone(), &cancel), peer); + assert_eq!(result.unwrap(), (!ack_first).then(|| vec![1])); + } + } + + #[tokio::test] + async fn exchange_rejects_unexpected_acknowledgements() { + let cancel = CancellationToken::new(); + let mut sink = tokio::io::sink(); + let mut reply = &[0, 0, 0, 1, 1u8][..]; + assert_eq!( + exchange(&mut sink, &mut reply, encode(1, &["query"]).unwrap(), &cancel).await.unwrap(), + Some(vec![1]) + ); + for cancelled in [false, true] { + if cancelled { + cancel.cancel(); + } + let mut duplicate_ack = &[0u8; 8][..]; + assert!(exchange(&mut sink, &mut duplicate_ack, encode(1, &["query"]).unwrap(), &cancel).await.is_err()); + } + let (mut peer, mut output) = tokio::io::duplex(4); + peer.write_u32(0).await.unwrap(); + let error = exchange(&mut sink, &mut output, encode(1, &["query"]).unwrap(), &cancel).await.unwrap_err(); + assert_eq!(error.message, cancel_timeout().message); + } + + #[test] + fn result_codec_preserves_null_and_rejects_incomplete_frames() { + let mut frame = + vec![1, 0, 0, 0, 1, 0, 0, 0, 1, b'n', 0, 0, 0, 3, b'i', b'n', b't', 1, 255, 255, 255, 255, 0, 0]; + frame.extend_from_slice(&(-1i64).to_be_bytes()); + let result = decode(&frame, "select", 0.).unwrap(); + assert_eq!(result.columns[0].name, "n"); + assert_eq!(result.rows, [vec![None]]); + for end in 0..frame.len() { + assert!(decode(&frame[..end], "", 0.).is_err()); + } + frame.push(0); + assert!(decode(&frame, "", 0.).is_err()); + assert!(decode(&[2], "", 0.).is_err()); + } +} diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index 4473c11b0..bd5d8ab05 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -4,6 +4,8 @@ pub mod catalog; mod clickhouse; +mod jdbc; +pub use jdbc::{DbJdbcDriver, jdbc_driver_classes}; pub mod conn; pub mod history; mod oracle; @@ -339,7 +341,7 @@ fn group_foreign_keys(rows: Vec>>, tables: &[CompletionTable] /// never contain `:`. /// Snowflake is HTTPS to a named host: a tunnel's local end cannot pass its certificate check. fn tunneled(driver: DbDriver) -> bool { - !matches!(driver, DbDriver::Sqlite | DbDriver::Snowflake) + !matches!(driver, DbDriver::Sqlite | DbDriver::Snowflake | DbDriver::Jdbc) } /// The database host and port the SSH host forwards to. @@ -759,7 +761,7 @@ impl DbManager { }; let (target, tunnel) = self.endpoint(source, ssh_secret, false).await?; self.restore_sso(source).await; - let connected = Pool::connect(&target, password.as_deref(), Some(&self.root)).await; + let connected = self.open_pool(&target, password.as_deref(), true).await; self.keep_sso(source).await; let pool = connected.map_err(|e| { through_tunnel( @@ -768,7 +770,13 @@ impl DbManager { tunnel.is_some().then(|| self.ssh_label(source.ssh.as_ref().expect("tunneled"))).as_deref(), ) })?; + if let Pool::Jdbc(p) = &pool { + let version = p.version.clone(); + pool.close().await; + return Ok(version); + } let version = match source.driver { + DbDriver::Jdbc => unreachable!("JDBC uses driver metadata"), DbDriver::Sqlite => "SELECT 'SQLite ' || sqlite_version()", DbDriver::Postgres | DbDriver::Clickhouse => "SELECT version()", DbDriver::Mysql => "SELECT CONCAT(@@version_comment, ' ', VERSION())", @@ -861,7 +869,7 @@ impl DbManager { let password = self.password(&source).await; let (target, tunnel) = self.endpoint(&source, None, true).await?; self.restore_sso(&source).await; - let connected = Pool::connect(&target, password.as_deref(), Some(&self.root)).await; + let connected = self.open_pool(&target, password.as_deref(), false).await; self.keep_sso(&source).await; let pool = match connected { Ok(p) => Arc::new(p), @@ -1071,7 +1079,10 @@ impl DbManager { if let Pool::Snowflake(p) = &*pool { return snowflake::meta::schemas(p, system).await; } - let rows = pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?; + let rows = match &*pool { + Pool::Jdbc(p) => p.metadata(&["schemas"]).await?, + _ => pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?, + }; Ok(rows.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect()) } @@ -1080,7 +1091,10 @@ impl DbManager { if let Pool::Snowflake(p) = &*pool { return snowflake::meta::tables(p, schema).await; } - let rows = pool.rows(&sql::tables(pool.driver(), schema), MAX_META_ROWS).await?; + let rows = match &*pool { + Pool::Jdbc(p) => p.metadata(&["tables", schema]).await?, + _ => pool.rows(&sql::tables(pool.driver(), schema), MAX_META_ROWS).await?, + }; Ok(rows .into_iter() .filter_map(|r| { @@ -1097,9 +1111,11 @@ impl DbManager { return snowflake::meta::table_details(p, schema, table).await; } let driver = pool.driver(); - let columns = pool - .rows(&sql::columns(driver, schema, table), MAX_META_ROWS) - .await? + let rows = match &*pool { + Pool::Jdbc(p) => p.metadata(&["columns", schema, table]).await?, + _ => pool.rows(&sql::columns(driver, schema, table), MAX_META_ROWS).await?, + }; + let columns = rows .into_iter() .filter_map(|r| { let mut it = r.into_iter(); @@ -1111,6 +1127,9 @@ impl DbManager { Some(ColumnInfo { name, data_type, nullable, default, primary_key }) }) .collect(); + if driver == DbDriver::Jdbc { + return Ok(TableDetails { columns, indexes: vec![], foreign_keys: vec![], triggers: vec![] }); + } let mut indexes: Vec = Vec::new(); for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? { let mut it = r.into_iter(); @@ -1271,6 +1290,7 @@ impl DbManager { rows.into_iter().filter_map(|r| r.into_iter().nth(i).flatten()).collect() }; match driver { + DbDriver::Jdbc => Err(IdeError::invalid("Custom JDBC sources do not provide vendor-specific DDL")), DbDriver::Sqlite => { let stmts = cells(pool.rows(&sql::sqlite_ddl(schema, name), MAX_META_ROWS).await?, 0); if stmts.is_empty() { @@ -1395,6 +1415,7 @@ impl DbManager { let driver = pool.driver(); let mut tables: Vec = Vec::new(); let rows = match &*pool { + Pool::Jdbc(p) => return self.jdbc_completion(id, p).await, Pool::Snowflake(p) => { tables = snowflake::meta::completion(p).await?; Vec::new() @@ -1515,6 +1536,9 @@ impl DbManager { schema: Option<&str>, ) -> IdeResult> { let driver = self.pool(id).await?.driver(); + if driver == DbDriver::Jdbc { + return Err(IdeError::invalid("Custom JDBC execution plans are unsupported")); + } if driver == DbDriver::Oracle { // EXPLAIN PLAN writes PLAN_TABLE; the plan is read (and cleaned up) separately. let plan_id = format!( @@ -1554,6 +1578,9 @@ impl DbManager { schema: Option<&str>, ) -> IdeResult { let pool = self.pool(id).await?; + if let Pool::Jdbc(p) = &*pool { + return p.query_in_schema(statement, skip, max_rows, cancel, schema).await; + } let session = self.sessions.lock().get(id).cloned(); let Some(session) = session else { if schema.is_none() { @@ -1595,6 +1622,9 @@ impl DbManager { /// Switches `id` between auto-commit and manual commit. Leaving manual /// mode rolls back what was not committed. pub async fn set_manual_commit(&self, id: &str, manual: bool) -> IdeResult<()> { + if manual && self.source(id)?.driver == DbDriver::Jdbc { + return Err(IdeError::invalid("Custom JDBC manual transactions are unsupported")); + } if manual { if self.source(id)?.driver == DbDriver::Clickhouse { return Err(IdeError::invalid("ClickHouse manual transactions are unsupported")); @@ -1614,6 +1644,9 @@ impl DbManager { if self.source(id).is_ok_and(|s| s.driver == DbDriver::Clickhouse) { return Err(IdeError::invalid("ClickHouse manual transactions are unsupported")); } + if self.source(id).is_ok_and(|s| s.driver == DbDriver::Jdbc) { + return Err(IdeError::invalid("Custom JDBC manual transactions are unsupported")); + } let session = self.sessions.lock().get(id).cloned(); let Some(session) = session else { return Ok(()) }; let mut held = session.lock().await; @@ -1649,8 +1682,22 @@ impl DbManager { ) -> IdeResult { let details = self.table_details(id, schema, table).await?; let pool = self.pool(id).await?; - let sql = sql::table_page(pool.driver(), schema, table, filter, sort, offset, limit); - let mut result = pool.execute(&sql, limit as usize, cancel).await?; + let mut result = if let Pool::Jdbc(p) = &*pool { + let q = &p.identifier_quote; + let names = [schema, table].into_iter().chain(sort.iter().map(|k| k.column.as_str())); + if q.is_empty() + && names.into_iter().any(|name| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')) + { + return Err(IdeError::invalid("This JDBC driver cannot quote the selected identifier")); + } + let quote = |s: &str| format!("{q}{}{q}", s.replace(q, &format!("{q}{q}"))); + let name = if schema.is_empty() { quote(table) } else { format!("{}.{}", quote(schema), quote(table)) }; + let sql = sql::table_select(&name, filter, sort, quote); + p.page(&sql, offset, limit, cancel).await? + } else { + let sql = sql::table_page(pool.driver(), schema, table, filter, sort, offset, limit); + pool.execute(&sql, limit as usize, cancel).await? + }; if result.columns.is_empty() { result.columns = details .columns @@ -1663,7 +1710,11 @@ impl DbManager { /// Applies the table editor's pending changes in one transaction. pub async fn apply_edits(&self, id: &str, schema: &str, table: &str, edits: &[DbRowEdit]) -> IdeResult { - if self.source(id)?.driver == DbDriver::Clickhouse { + let source = self.source(id)?; + if source.read_only { + return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only")); + } + if source.driver == DbDriver::Clickhouse { return Err(IdeError::invalid("ClickHouse table editing is unsupported")); } let pool = self.pool(id).await?; diff --git a/crates/ide-db/src/plan.rs b/crates/ide-db/src/plan.rs index 55637f98d..bce08ead7 100644 --- a/crates/ide-db/src/plan.rs +++ b/crates/ide-db/src/plan.rs @@ -36,7 +36,7 @@ pub fn explain_statement(driver: DbDriver, statement: &str) -> String { DbDriver::Sqlite => format!("EXPLAIN QUERY PLAN {s}"), DbDriver::Postgres => format!("EXPLAIN (FORMAT JSON) {s}"), DbDriver::Clickhouse => format!("EXPLAIN json = 1 {s}"), - DbDriver::Mysql => format!("EXPLAIN {s}"), + DbDriver::Mysql | DbDriver::Jdbc => format!("EXPLAIN {s}"), DbDriver::SqlServer => format!("SET SHOWPLAN_TEXT ON; {s}"), DbDriver::Oracle => format!("EXPLAIN PLAN FOR {s}"), DbDriver::Snowflake => format!("EXPLAIN USING TABULAR {s}"), @@ -77,6 +77,7 @@ pub fn parse(driver: DbDriver, result: &QueryResult) -> IdeResult> let names: Vec<&str> = result.columns.iter().map(|c| c.name.as_str()).collect(); Ok(mysql(&names, &result.rows)) } + DbDriver::Jdbc => Err(IdeError::invalid("Custom JDBC execution plans are unsupported")), DbDriver::SqlServer => Ok(Vec::new()), DbDriver::Snowflake => { let names: Vec<&str> = result.columns.iter().map(|c| c.name.as_str()).collect(); diff --git a/crates/ide-db/src/source.rs b/crates/ide-db/src/source.rs index 1815e646a..b7e316b57 100644 --- a/crates/ide-db/src/source.rs +++ b/crates/ide-db/src/source.rs @@ -23,12 +23,13 @@ pub enum DbDriver { /// Oracle Database (pure-Rust thin driver, no client library). Oracle, Snowflake, + Jdbc, } impl DbDriver { pub fn default_port(self) -> Option { match self { - DbDriver::Sqlite => None, + DbDriver::Sqlite | DbDriver::Jdbc => None, DbDriver::Postgres => Some(5432), DbDriver::Mysql => Some(3306), DbDriver::SqlServer => Some(1433), @@ -191,6 +192,9 @@ pub struct DataSource { pub id: String, pub name: String, pub driver: DbDriver, + /// An app-wide driver profile id; classpaths never come from a project. + #[serde(skip_serializing_if = "String::is_empty")] + pub jdbc_driver: String, pub host: String, pub port: Option, pub database: String, @@ -237,6 +241,7 @@ impl Default for DataSource { id: String::new(), name: String::new(), driver: DbDriver::Sqlite, + jdbc_driver: String::new(), host: "localhost".into(), port: None, database: String::new(), @@ -390,6 +395,12 @@ impl DataSource { /// database, user, SSL and driver properties come from the URL (properties /// of the Advanced tab still apply after the URL's). pub fn resolved(&self) -> IdeResult { + if self.driver == DbDriver::Jdbc { + if !self.url.starts_with("jdbc:") { + return Err(IdeError::invalid("Enter a JDBC URL starting with jdbc:")); + } + return Ok(self.clone()); + } if !self.url_only { return Ok(self.clone()); } @@ -476,7 +487,7 @@ impl DataSource { /// The password written in the URL of a [`DataSource::url_only`] data source. pub fn url_password(&self) -> Option { - if !self.url_only { + if self.driver == DbDriver::Jdbc || !self.url_only { return None; } parse_url(&self.url).ok()?.password @@ -491,7 +502,11 @@ struct SourcesFile { /// The project's data sources. pub fn load(root: &Path) -> IdeResult> { - read(&project_dir::path(root, FILE)) + let mut sources = read(&project_dir::path(root, FILE))?; + for source in &mut sources { + source.global = false; + } + Ok(sources) } /// Saves the project's data sources. diff --git a/crates/ide-db/src/sql.rs b/crates/ide-db/src/sql.rs index 764cc397b..8dff30d66 100644 --- a/crates/ide-db/src/sql.rs +++ b/crates/ide-db/src/sql.rs @@ -70,6 +70,7 @@ pub fn sqlserver_databases() -> &'static str { pub fn schemas(driver: DbDriver, system: bool) -> &'static str { match driver { + DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"), DbDriver::Sqlite => "SELECT name FROM pragma_database_list WHERE name <> 'temp' ORDER BY seq", DbDriver::Clickhouse if system => "SELECT name FROM system.databases ORDER BY name", DbDriver::Clickhouse => { @@ -114,6 +115,7 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str { /// Rows: `name, kind` where kind is `table`, `view` or `materialized view`. pub fn tables(driver: DbDriver, schema: &str) -> String { match driver { + DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"), DbDriver::Clickhouse => format!( "SELECT name, CASE engine WHEN 'View' THEN 'view' WHEN 'MaterializedView' THEN 'materialized view' \ WHEN 'WindowView' THEN 'view' ELSE 'table' END FROM system.tables \ @@ -164,6 +166,7 @@ const SNOWFLAKE_TYPE: &str = "CASE WHEN data_type = 'NUMBER' THEN 'NUMBER(' || n pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String { let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table)); match driver { + DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"), DbDriver::Clickhouse => format!( "SELECT name, type, CASE WHEN startsWith(type, 'Nullable(') \ OR startsWith(type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, \ @@ -225,6 +228,7 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String { pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String { let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table)); match driver { + DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"), DbDriver::Clickhouse => format!( "SELECT * FROM (SELECT 'PRIMARY KEY' AS index_name, 0 AS is_unique, primary_key AS expression \ FROM system.tables WHERE database = {s} AND name = {t} AND primary_key != '' \ @@ -269,6 +273,7 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String { /// for SQL completion, grouped by table in column order. pub fn completion_columns(driver: DbDriver) -> &'static str { match driver { + DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"), DbDriver::Clickhouse => { "SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \ WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \ @@ -357,6 +362,7 @@ pub fn completion_columns(driver: DbDriver) -> &'static str { /// when the key references the primary key implicitly. pub fn foreign_keys(driver: DbDriver) -> &'static str { match driver { + DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"), DbDriver::Clickhouse => "SELECT '', '', '', '', '', '', '' WHERE 0", DbDriver::Snowflake => "SELECT '', '', '', '', '', '', '' WHERE 1 = 0", DbDriver::Sqlite => { @@ -409,6 +415,7 @@ pub fn foreign_keys(driver: DbDriver) -> &'static str { pub fn table_foreign_keys(driver: DbDriver, schema: &str, table: &str) -> String { let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table)); match driver { + DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"), DbDriver::Clickhouse | DbDriver::Snowflake => foreign_keys(driver).to_owned(), DbDriver::Sqlite => format!( "SELECT {s}, {t}, f.id, f.\"from\", {s}, f.\"table\", f.\"to\" FROM pragma_foreign_key_list({t}, {s}) f ORDER BY f.id, f.seq" @@ -432,7 +439,7 @@ pub fn table_foreign_keys(driver: DbDriver, schema: &str, table: &str) -> String pub fn current_schema(driver: DbDriver) -> Option<&'static str> { match driver { DbDriver::Clickhouse => Some("SELECT currentDatabase()"), - DbDriver::Sqlite => None, + DbDriver::Sqlite | DbDriver::Jdbc => None, DbDriver::Postgres => Some("SELECT current_schema()"), DbDriver::Mysql => Some("SELECT DATABASE()"), DbDriver::SqlServer => Some("SELECT DB_NAME()"), @@ -446,7 +453,7 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> { /// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs). pub fn use_schema(driver: DbDriver, schema: &str) -> Option { match driver { - DbDriver::Sqlite | DbDriver::Clickhouse => None, + DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc => None, DbDriver::Postgres => Some(format!("SET search_path TO {}", quote_ident(driver, schema))), DbDriver::Mysql | DbDriver::SqlServer => Some(format!("USE {}", quote_ident(driver, schema))), DbDriver::Oracle => Some(format!("ALTER SESSION SET CURRENT_SCHEMA = {}", quote_ident(driver, schema))), @@ -462,17 +469,13 @@ pub struct SortKey { pub descending: bool, } -/// One page of a table: `limit + 1` rows so the caller knows whether more exist. -pub fn table_page( - driver: DbDriver, - schema: &str, - table: &str, +pub(crate) fn table_select( + qualified_name: &str, filter: Option<&str>, sort: &[SortKey], - offset: u64, - limit: u64, + quote: impl Fn(&str) -> String, ) -> String { - let mut sql = format!("SELECT * FROM {}", qualified(driver, schema, table)); + let mut sql = format!("SELECT * FROM {}", qualified_name); if let Some(f) = filter.map(str::trim).filter(|f| !f.is_empty()) { let mut f = f.strip_prefix("WHERE ").or_else(|| f.strip_prefix("where ")).unwrap_or(f); if let Some(i) = f.find(';') { @@ -484,12 +487,24 @@ pub fn table_page( } } if !sort.is_empty() { - let keys: Vec = sort - .iter() - .map(|k| format!("{}{}", quote_ident(driver, &k.column), if k.descending { " DESC" } else { "" })) - .collect(); + let keys: Vec = + sort.iter().map(|k| format!("{}{}", quote(&k.column), if k.descending { " DESC" } else { "" })).collect(); sql.push_str(&format!(" ORDER BY {}", keys.join(", "))); } + sql +} + +/// One page of a table: `limit + 1` rows so the caller knows whether more exist. +pub fn table_page( + driver: DbDriver, + schema: &str, + table: &str, + filter: Option<&str>, + sort: &[SortKey], + offset: u64, + limit: u64, +) -> String { + let mut sql = table_select(&qualified(driver, schema, table), filter, sort, |name| quote_ident(driver, name)); if driver == DbDriver::SqlServer { if sort.is_empty() { sql.push_str(" ORDER BY (SELECT 1)"); @@ -535,6 +550,9 @@ fn where_key(driver: DbDriver, key: &[CellValue]) -> String { /// The DML statement for `edit`. Values are written as quoted literals, which /// every supported database coerces to the column type. pub fn edit_statement(driver: DbDriver, schema: &str, table: &str, edit: &DbRowEdit) -> Result { + if driver == DbDriver::Jdbc { + return Err("Custom JDBC table editing is unsupported".into()); + } if driver == DbDriver::Clickhouse { return Err("ClickHouse table editing is unsupported: primary keys do not uniquely identify rows and edits require transactions".into()); } @@ -631,6 +649,7 @@ pub fn postgres_ddl_indexes(oid: u32) -> String { pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String { let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table)); match driver { + DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"), DbDriver::Clickhouse => "SELECT '', '', '' WHERE 0".to_owned(), DbDriver::Snowflake => "SELECT '', '', '' WHERE 1 = 0".to_owned(), DbDriver::Sqlite => format!( @@ -691,7 +710,7 @@ pub fn postgres_legacy(sql: &str) -> Option { pub fn routines(driver: DbDriver, schema: &str) -> Option { let s = quote_literal(driver, schema); match driver { - DbDriver::Sqlite | DbDriver::Clickhouse => None, + DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc => None, // Functions of extensions are left out, as in IDEA. DbDriver::Postgres => Some(format!( "SELECT p.proname, CASE WHEN p.prokind = 'p' THEN 'procedure' ELSE 'function' END, \ diff --git a/crates/ide-db/tests/jdbc.rs b/crates/ide-db/tests/jdbc.rs new file mode 100644 index 000000000..1d772b046 --- /dev/null +++ b/crates/ide-db/tests/jdbc.rs @@ -0,0 +1,215 @@ +use ide_core::{CancellationToken, IdeResult}; +use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, SortKey}; +use std::{path::Path, sync::Arc}; + +fn manager(dir: &Path) -> DbManager { + let ssh = Arc::new(ide_ssh::SshManager::new(dir.join("ssh.json"))); + DbManager::new(dir.join("project"), dir.join("passwords.json"), dir.join("history.json"), ssh) + .with_global_sources(dir.join("global")) +} + +#[tokio::test] +async fn jdbc_profiles_persist_and_project_files_cannot_start_drivers() -> IdeResult<()> { + let tmp = tempfile::tempdir()?; + let jar = tmp.path().join("fixture.jar"); + std::fs::write(&jar, [])?; + let db = manager(tmp.path()); + db.save_jdbc_driver(DbJdbcDriver { + id: "fixture".into(), + name: "Test".into(), + jars: vec![jar.display().to_string()], + class_name: "test.Driver".into(), + url_template: "jdbc:test:".into(), + })?; + let reopened = manager(tmp.path()); + assert_eq!(reopened.jdbc_drivers()?[0].class_name, "test.Driver"); + let source = DataSource { + id: "local".into(), + name: "local".into(), + driver: DbDriver::Jdbc, + jdbc_driver: "fixture".into(), + url: "jdbc:test:".into(), + ..Default::default() + }; + reopened.save_sources(vec![source.clone()]).await?; + let denied = reopened.pool("local").await.err().expect("project JDBC requires explicit approval"); + assert!(denied.message.contains("Review this project")); + let readonly = DataSource { read_only: true, ..source.clone() }; + reopened.save_sources(vec![readonly]).await?; + let err = reopened.apply_edits("local", "main", "sample", &[]).await.unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::PermissionDenied); + reopened.approve_jdbc_source(&source)?; + let mut changed = source.clone(); + changed.url.push_str("changed"); + reopened.save_sources(vec![changed]).await?; + assert!(reopened.pool("local").await.err().unwrap().message.contains("Review this project")); + let mut global = source; + global.global = true; + reopened.save_sources(vec![global]).await?; + assert!(reopened.remove_jdbc_driver("fixture").is_err()); + reopened.save_sources(vec![]).await?; + reopened.remove_jdbc_driver("fixture")?; + assert!(manager(tmp.path()).jdbc_drivers()?.is_empty()); + Ok(()) +} + +#[tokio::test] +#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"] +async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> { + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR"); + assert_eq!(ide_db::jdbc_driver_classes(std::slice::from_ref(&jar))?, ["org.duckdb.DuckDBDriver"]); + db.save_jdbc_driver(DbJdbcDriver { + id: "duck".into(), + name: "DuckDB".into(), + jars: vec![jar], + class_name: "org.duckdb.DuckDBDriver".into(), + url_template: "jdbc:duckdb:".into(), + })?; + let source = DataSource { + id: "test".into(), + name: "DuckDB".into(), + driver: DbDriver::Jdbc, + global: true, + jdbc_driver: "duck".into(), + url: "jdbc:duckdb:local.duckdb".into(), + ..Default::default() + }; + assert!(db.test(&source, None, None).await?.to_lowercase().contains("duckdb")); + db.save_sources(vec![source]).await?; + let db = manager(tmp.path()); + let c = CancellationToken::new(); + db.execute("test", "create table items(id int primary key, label varchar)", 1, &c).await?; + db.execute("test", "insert into items values (1, NULL), (2, 'row')", 1, &c).await?; + assert!(db.schemas("test").await?.iter().any(|v| v == "main")); + assert!(db.tables("test", "main").await?.iter().any(|v| v.name == "items")); + let details = db.table_details("test", "main", "items").await?; + assert_eq!(details.columns.len(), 2); + let result = db.execute("test", "select id, label from items order by id", 1, &c).await?; + assert!(result.has_more); + assert_eq!(result.rows, vec![vec![Some("1".into()), None]]); + assert_eq!(result.columns[1].name, "label"); + assert_eq!(db.completion("test").await?.default_schema, "main"); + db.execute("test", "create temporary table session_marker as select 42 as id", 1, &c).await?; + let stop = CancellationToken::new(); + let (cancelled, ()) = + tokio::join!(db.execute("test", "select sum(sin(i)) from range(1000000000) t(i)", 1, &stop), async { + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + stop.cancel(); + },); + assert_eq!(cancelled.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled); + let marker = db.execute("test", "select id from session_marker", 1, &c).await?; + assert_eq!(marker.rows, [vec![Some("42".into())]]); + let sort = [SortKey { column: "id".into(), descending: false }]; + let first = db.table_page("test", "main", "items", None, &sort, 0, 1, &c).await?.result; + assert_eq!(first.rows, result.rows); + assert!(first.has_more); + let last = db.table_page("test", "main", "items", None, &sort, 1, 1, &c).await?.result; + assert_eq!(last.rows, vec![vec![Some("2".into()), Some("row".into())]]); + assert!(!last.has_more); + let past = db.table_page("test", "main", "items", None, &sort, 2, 1, &c).await?.result; + assert!(past.rows.is_empty() && !past.has_more); + db.disconnect("test").await; + let reopened = manager(tmp.path()); + assert_eq!(reopened.execute("test", "select count(*) from items", 1, &c).await?.rows, [vec![Some("2".into())]]); + reopened.disconnect("test").await; + Ok(()) +} + +#[tokio::test] +#[ignore = "requires CLICKHOUSE_JDBC_CLASSPATH and a loopback ClickHouse fixture on CLICKHOUSE_JDBC_TEST_PORT"] +async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> { + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + let jars: Vec = + std::env::split_paths(&std::env::var_os("CLICKHOUSE_JDBC_CLASSPATH").expect("CLICKHOUSE_JDBC_CLASSPATH")) + .map(|p| p.display().to_string()) + .collect(); + let classes = ide_db::jdbc_driver_classes(&jars)?; + assert_eq!(classes.first().map(String::as_str), Some("com.clickhouse.jdbc.ClickHouseDriver")); + let port: u16 = std::env::var("CLICKHOUSE_JDBC_TEST_PORT").unwrap().parse().unwrap(); + db.save_jdbc_driver(DbJdbcDriver { + id: "clickhouse".into(), + name: "ClickHouse JDBC".into(), + jars, + class_name: "com.clickhouse.jdbc.ClickHouseDriver".into(), + url_template: "jdbc:clickhouse://".into(), + })?; + let source = DataSource { + id: "test".into(), + name: "ClickHouse JDBC".into(), + driver: DbDriver::Jdbc, + jdbc_driver: "clickhouse".into(), + url: format!("jdbc:clickhouse://127.0.0.1:{port}/default"), + user: "fixture".into(), + read_only: true, + ..Default::default() + }; + let password = "local-fixture"; + assert!(db.test(&source, Some(password.into()), None).await?.contains("ClickHouse")); + db.approve_jdbc_source(&source)?; + db.save_sources(vec![source]).await?; + db.set_password("test", Some(password.into()), false).await?; + assert!(db.schemas("test").await?.iter().any(|v| v == "system")); + assert!(db.tables("test", "system").await?.iter().any(|v| v.name == "one")); + let cols = db.table_details("test", "system", "one").await?.columns; + assert!(cols.iter().any(|col| col.name == "dummy")); + let r = db.execute("test", "SELECT number FROM numbers(3) ORDER BY number", 2, &CancellationToken::new()).await?; + assert_eq!(r.rows.len(), 2); + assert!(r.has_more); + let c = CancellationToken::new(); + let page = db.table_page("test", "system", "one", None, &[], 0, 1, &c).await?.result; + assert_eq!(page.rows.len(), 1); + assert!(!page.has_more); + let past = db.table_page("test", "system", "one", None, &[], 1, 1, &c).await?.result; + assert!(past.rows.is_empty() && !past.has_more); + db.disconnect("test").await; + Ok(()) +} + +#[tokio::test] +#[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"] +async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> { + use std::time::Duration; + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + let started = tmp.path().join("started"); + db.save_jdbc_driver(DbJdbcDriver { + id: "fixture".into(), + name: "Fixture".into(), + jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()], + class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(), + url_template: String::new(), + })?; + let source = DataSource { + id: "test".into(), + name: "Fixture".into(), + driver: DbDriver::Jdbc, + global: true, + read_only: true, + jdbc_driver: "fixture".into(), + url: format!("jdbc:fixture:{}", started.display()), + ..Default::default() + }; + db.test(&source, None, None).await?; + db.save_sources(vec![source]).await?; + let normal = CancellationToken::new(); + assert!(db.execute("test", "write", 1, &normal).await.unwrap_err().message.contains("read-only")); + let stop = CancellationToken::new(); + let (result, ()) = tokio::time::timeout(Duration::from_secs(12), async { + tokio::join!(db.execute("test", "ignore cancel", 1, &stop), async { + while !started.is_file() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + stop.cancel(); + }) + }) + .await + .expect("driver cancellation must be bounded"); + assert!(result.unwrap_err().message.contains("Reconnect")); + db.disconnect("test").await; + assert_eq!(db.execute("test", "after reconnect", 1, &normal).await?.affected, Some(1.0)); + db.disconnect("test").await; + Ok(()) +} diff --git a/crates/ide-host/src/ops/db.rs b/crates/ide-host/src/ops/db.rs index 632a6d00a..dd5877c1c 100644 --- a/crates/ide-host/src/ops/db.rs +++ b/crates/ide-host/src/ops/db.rs @@ -24,6 +24,34 @@ pub struct StatementOutcome { pub error: Option, } +#[command(trust = trusted)] +pub fn db_approve_jdbc_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> { + host.project(window)?.db.approve_jdbc_source(&source) +} + +#[command(trust = trusted)] +pub async fn db_jdbc_driver_classes(host: &Host, window: &str, jars: Vec) -> IdeResult> { + host.project(window)?; + tokio::task::spawn_blocking(move || ide_db::jdbc_driver_classes(&jars)) + .await + .map_err(|e| IdeError::internal(e.to_string()))? +} + +#[command(trust = trusted)] +pub fn db_jdbc_drivers(host: &Host, window: &str) -> IdeResult> { + host.project(window)?.db.jdbc_drivers() +} + +#[command(trust = trusted)] +pub fn db_save_jdbc_driver(host: &Host, window: &str, driver: ide_db::DbJdbcDriver) -> IdeResult<()> { + host.project(window)?.db.save_jdbc_driver(driver) +} + +#[command(trust = trusted)] +pub fn db_remove_jdbc_driver(host: &Host, window: &str, id: String) -> IdeResult<()> { + host.project(window)?.db.remove_jdbc_driver(&id) +} + #[command(trust = trusted)] pub fn db_sources(host: &Host, window: &str) -> IdeResult> { // The data sources configured for the project (the tree's roots). @@ -514,6 +542,11 @@ ide_command::domain!( db_explain, db_finish_transaction, db_history, + db_jdbc_driver_classes, + db_jdbc_drivers, + db_approve_jdbc_source, + db_save_jdbc_driver, + db_remove_jdbc_driver, db_object_ddl, db_remove_history, db_retain_catalog, diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index b6ee57400..80760880e 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -86,6 +86,11 @@ pub(crate) fn java_runs(java: &Path) -> bool { runnable } +/// First runnable Java installation in discovery order, including standalone JREs. +pub fn java_runtime(jdks: &[Jdk], min_java: u32) -> Option<&Jdk> { + jdks.iter().find(|j| j.major >= min_java && java_runs(&java_executable(&j.home))) +} + fn project_jdk_is_usable(jdk: &Jdk) -> bool { jdk.home.join("bin").join(crate::exe("javac")).is_file() && (jdk.major < 9 || ide_core::java_runtime::supports_java_bundles(&jdk.home)) @@ -748,6 +753,16 @@ pub(crate) fn write_test_java(home: &Path) { mod tests { use super::*; + #[test] + fn java_runtime_accepts_a_jre_without_a_compiler() { + let tmp = tempfile::tempdir().unwrap(); + let jre = test_jdk(tmp.path(), 17, "jre"); + std::fs::remove_file(jre.home.join("bin").join(crate::exe("javac"))).unwrap(); + let jdks = [test_jdk(tmp.path(), 11, "old"), jre.clone()]; + assert_eq!(java_runtime(&jdks, 17), Some(&jre)); + assert_eq!(java_runtime(&jdks, 21), None); + } + fn test_jdk(root: &Path, major: u32, name: &str) -> Jdk { let home = root.join(name.trim_start_matches('/')); std::fs::create_dir_all(home.join("bin")).unwrap(); @@ -1619,6 +1634,16 @@ pub fn usages_bundle(data_dir: &Path) -> Option { ) } +/// Extracts the JDBC bridge into the application's data directory. +pub fn jdbc_bridge_jar(data_dir: &Path) -> Option { + install_bundle( + data_dir, + "jdbc-bridge", + "1.0.0", + include_bytes!("../../../java/jdbc-bridge/openidea-jdbc-bridge.jar"), + ) +} + /// Installs the app-owned JDT LS bundle that inspects java-debug's JVMs. pub fn jvm_inspect_bundle(data_dir: &Path) -> Option { install_bundle( diff --git a/docs/en/guide/database.mdx b/docs/en/guide/database.mdx index c41090b7e..f0be531b1 100644 --- a/docs/en/guide/database.mdx +++ b/docs/en/guide/database.mdx @@ -3,7 +3,7 @@ title: "Databases" description: "Connect to SQL databases, browse schemas, run queries in a console, and view, edit, import and export data." --- -The **Database** tool window connects to SQLite, PostgreSQL, MySQL/MariaDB, Microsoft SQL Server, Oracle, ClickHouse and Snowflake, plus databases that speak one of their protocols. Drivers are built into the IDE; there are no JDBC drivers to download. +The **Database** tool window connects to SQLite, PostgreSQL, MySQL/MariaDB, Microsoft SQL Server, Oracle, ClickHouse and Snowflake, plus databases that speak one of their protocols. These presets use built-in drivers. You can also connect with a vendor JDBC driver installed locally. Open it from **Tools › Database** or **View › Tool Windows › Database**. The **Tools** menu also has **New Data Source…** and **Open Query Console**. @@ -23,6 +23,16 @@ Open it from **Tools › Database** or **View › Tool Windows › Database**. T Presets set the default port and, where needed, SSL (for example Redshift, Neon and Supabase require SSL). +## Custom JDBC drivers + +Choose **New › Data Source › Custom JDBC**, then **Manage Drivers…**. Add a named profile with the vendor's driver JAR, any dependency JARs, the fully qualified driver class, and an optional JDBC URL template. OpenIDEA reads the driver classes declared in the selected JARs. You can choose a different class or enter its full name manually. Use `{host}`, `{port}`, `{database}` or `{file}` in a template to get matching connection fields, or edit the JDBC URL directly. Only import drivers you trust. OpenIDEA loads their code in a separate process using an installed Java 17 or newer runtime. + +Select the profile, enter the vendor's JDBC URL, and use the **User**, **Password**, and **Advanced** fields for credentials and driver properties. The URL and Advanced properties are stored in the data source configuration. Put credentials in the password field to use the existing OS credential store. On Linux, saving a password requires a running Secret Service. You can also enter the password for the current session. The **Read-only** option asks the JDBC driver for a read-only connection. Use a database account with read-only privileges to enforce it. Cancelling a query keeps the session and its temporary tables when the driver stops the statement. If the driver does not respond within three seconds, OpenIDEA closes the session. A submitted statement can still finish on the server. **Test Connection** reports the database product and version. Schema, table and column browsing use JDBC metadata; the SQL console supports auto-commit queries and updates. Vendor-specific DDL, execution plans and table-grid writes are unavailable for custom drivers. + +For a file-backed database, use an absolute path to choose its location. Relative paths start in the persistent `jdbc/files` folder inside OpenIDEA’s application data directory. + +Profiles are reused across projects. If a project file changes a connection's URL or properties outside the IDE, review the settings in the data source dialog and save them before reconnecting. + ## Add a data source Click **+** in the Database tool window (or press `⌘N` / `Alt+Insert` there) and choose: @@ -205,7 +215,7 @@ Limits: `TIMESTAMP_LTZ` values are shown in UTC; SSH tunnels are not offered; re ## Not supported -- MongoDB, Redis, BigQuery and other non-listed databases; JDBC drivers. +- Native drivers for MongoDB, Redis and BigQuery. - SQL Server `GO` batch separators. - A "run the whole console" action (use a selection, or **Run SQL Script…**). - Exporting more than the loaded page. diff --git a/docs/zh/guide/database.mdx b/docs/zh/guide/database.mdx index cd3c77321..46aae10c2 100644 --- a/docs/zh/guide/database.mdx +++ b/docs/zh/guide/database.mdx @@ -3,7 +3,7 @@ title: "数据库" description: "连接 SQL 数据库、浏览架构、在查询控制台中执行查询,以及查看、编辑、导入和导出数据。" --- -**数据库** 工具窗口可以连接 SQLite、PostgreSQL、MySQL/MariaDB、Microsoft SQL Server、Oracle、ClickHouse 和 Snowflake,以及兼容这些协议的数据库。驱动内置在 IDE 中,不需要下载 JDBC 驱动。 +**数据库** 工具窗口可以连接 SQLite、PostgreSQL、MySQL/MariaDB、Microsoft SQL Server、Oracle、ClickHouse 和 Snowflake,以及兼容这些协议的数据库。这些预设使用 IDE 内置的驱动,也可以选择本地安装的厂商 JDBC 驱动。 通过 **工具 › 数据库** 或 **视图 › 工具窗口 › 数据库** 打开。**工具** 菜单中还有 **新建数据源…** 和 **Open Query Console**(打开查询控制台)。 @@ -23,6 +23,16 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行 预设会填好默认端口,必要时还会设置 SSL(例如 Redshift、Neon 和 Supabase 要求 SSL)。 +## 自定义 JDBC 驱动 + +选择 **新建 › 数据源 › 自定义 JDBC**,然后选择 **管理驱动…**。为驱动配置命名,添加厂商提供的驱动 JAR 及依赖 JAR,填写完整的驱动类名和可选的 JDBC URL 模板。请仅导入可信来源的驱动。OpenIDEA 使用已安装的 Java 17 或更高版本运行时在单独的进程中加载驱动。 IDE 会读取 JAR 声明的驱动类,也支持手动输入完整类名。URL 模板支持 `{host}`、`{port}`、`{database}` 和 `{file}`,也可直接填写 JDBC URL。 URL 和高级属性会写入数据源配置,密码请填在密码栏,以使用系统凭据存储。“只读”选项会请求 JDBC 驱动建立只读连接。使用具备只读权限的数据库账号可强制限制写入。取消查询时,如果驱动停止了语句,会话及其临时表会保留。如果驱动在三秒内未响应,OpenIDEA 会关闭该会话。已提交的语句仍可能在服务器上完成。 + +选择驱动配置,填写厂商的 JDBC URL,在 **用户**、**密码** 和 **高级** 中设置凭据和驱动属性。通过密码字段输入的密码可以保存到系统凭据库。在 Linux 上,保存密码需要正在运行的 Secret Service;也可以仅为当前会话输入密码。**测试连接** 显示数据库产品和版本。可以通过 JDBC 元数据浏览模式、表和列,在 SQL 控制台中查询或以自动提交方式更新数据。自定义驱动不支持厂商特有的 DDL、执行计划或表格编辑。 + +文件数据库可使用绝对路径指定存储位置。相对路径以 OpenIDEA 应用数据目录下的持久化 `jdbc/files` 文件夹为起点。 + +驱动配置可以跨项目复用。在 IDE 外更改项目数据源的 URL 或连接属性后,需要在数据源对话框中检查并保存设置,才能重新连接。 + ## 添加数据源 在数据库工具窗口中点击 **+**(或在窗口内按 `⌘N` / `Alt+Insert`),然后选择: @@ -200,7 +210,7 @@ Oracle 的架构就是数据库用户;系统账户只在勾选 **显示内部 ## 暂不支持 -- MongoDB、Redis、BigQuery 等未列出的数据库,以及 JDBC 驱动。 +- MongoDB、Redis 和 BigQuery 的原生驱动。 - SQL Server 的 `GO` 批处理分隔符。 - “执行整个控制台”的操作(请选中后执行,或使用 **运行 SQL 脚本…**)。 - 导出超出已加载页面的数据。 diff --git a/e2e/jdbc-source.spec.ts b/e2e/jdbc-source.spec.ts new file mode 100644 index 000000000..f84f36378 --- /dev/null +++ b/e2e/jdbc-source.spec.ts @@ -0,0 +1,122 @@ +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +test("configures a local JDBC profile and a source through mocked IPC", async ({ workbench: page }, info) => { + await stubDesktop(page); + await page.evaluate(async () => { + const drivers: Record[] = []; + let sources: Record[] = []; + Object.assign(window.__ipc.handlers, { + db_jdbc_drivers: () => drivers, + db_jdbc_driver_classes: () => ["org.example.jdbc.Driver"], + db_save_jdbc_driver: ({ driver }: { driver: Record }) => { + const at = drivers.findIndex((d) => d.id === driver.id); + if (at < 0) drivers.push(driver); + else drivers[at] = driver; + return null; + }, + db_remove_jdbc_driver: ({ id }: { id: string }) => { + drivers.splice( + drivers.findIndex((d) => d.id === id), + 1, + ); + return null; + }, + file_dialog_needs_gtk: () => false, + "plugin:dialog|open": () => ["/mock/driver.jar", "/mock/dependency.jar"], + db_test: () => "Mock JDBC database", + db_approve_jdbc_source: () => null, + db_save_sources: ({ sources: value }: { sources: Record[] }) => { + sources = value; + return null; + }, + db_sources: () => sources, + db_connected: () => [], + db_set_password: () => null, + }); + const storePath = "/src/features/database/store.ts"; + const { openSourceDialog } = await import(/* @vite-ignore */ storePath); + openSourceDialog(null, { + driver: "clickhouse", + name: "Mock connection", + host: "example.invalid", + port: 8443, + ssl: "verifyFull", + sslCaFile: "/mock/ca.pem", + sslCertFile: "/mock/client.pem", + sslKeyFile: "/mock/client.key", + }); + }); + const source = page.getByRole("dialog", { name: "New Data Source", exact: true }); + await source.getByRole("tab", { name: "SSH/SSL", exact: true }).click(); + await source.screenshot({ + path: info.outputPath("mock-native-clickhouse-before-switch.png"), + animations: "disabled", + }); + await source.getByRole("tab", { name: "General", exact: true }).click(); + await source.getByRole("button", { name: "Data source type", exact: true }).click(); + await page.getByRole("option", { name: "Custom JDBC", exact: true }).click(); + await expect(source.getByRole("tab", { name: "SSH/SSL", exact: true })).toHaveCount(0); + await expect(source.locator("#db-url")).toHaveValue(""); + await source.getByRole("button", { name: "Manage Drivers…", exact: true }).click(); + const profiles = page.getByRole("dialog", { name: "JDBC Driver Profiles", exact: true }); + await profiles.getByRole("button", { name: "Add…", exact: true }).click(); + const editor = page.getByRole("dialog", { name: "Add JDBC Driver", exact: true }); + await editor.getByLabel("Name:", { exact: true }).fill("Example local driver"); + await editor.getByRole("button", { name: "Add JARs…", exact: true }).click(); + await expect(editor.getByText("dependency.jar", { exact: true })).toBeVisible(); + await expect(editor.getByLabel("Driver class:", { exact: true })).toHaveValue("org.example.jdbc.Driver"); + await editor.getByLabel("URL template:", { exact: true }).fill("jdbc:example://{host}/{database}"); + await editor.screenshot({ path: info.outputPath("jdbc-profile-editor.png"), animations: "disabled" }); + await editor.getByRole("button", { name: "Save", exact: true }).click(); + const trust = page.getByRole("dialog", { name: "Trust JDBC Driver?", exact: true }); + await expect(trust).toContainText("execute local code with your user permissions"); + expect(await ipcCalls(page, "db_save_jdbc_driver")).toHaveLength(0); + await trust.screenshot({ path: info.outputPath("mock-jdbc-driver-trust.png"), animations: "disabled" }); + await trust.getByRole("button", { name: "Trust and Save", exact: true }).click(); + await profiles.getByRole("button", { name: "Use Driver", exact: true }).click(); + await expect(source.getByRole("button", { name: "JDBC driver profile", exact: true })).toHaveText( + "Example local driver", + ); + await source.getByLabel("Host:", { exact: true }).fill("example.invalid"); + await source.getByLabel("Database:", { exact: true }).fill("catalog"); + await expect(source.locator("#db-url")).toHaveValue("jdbc:example://example.invalid/catalog"); + await source.screenshot({ path: info.outputPath("jdbc-template.png"), animations: "disabled" }); + const url = "jdbc:example://example.invalid/catalog?ssl=true"; + await source.locator("#db-url").fill(url); + const test = source.getByRole("button", { name: "Test Connection", exact: true }); + await expect(test).toBeDisabled(); + await source.getByRole("checkbox", { name: "I have configured JDBC connection security.", exact: true }).check(); + await source.locator("#db-user").fill("example-user"); + await source.locator("#db-password").fill("mock secret"); + await source.screenshot({ path: info.outputPath("mock-jdbc-source-after-switch.png"), animations: "disabled" }); + await source.getByRole("tab", { name: "Options", exact: true }).click(); + await expect(source.getByRole("button", { name: "Transaction control", exact: true })).toHaveCount(0); + await source.getByRole("checkbox", { name: "Read-only", exact: true }).check(); + await expect( + source.getByText("For read-only access, use a database account with read-only privileges."), + ).toBeVisible(); + await source.screenshot({ path: info.outputPath("jdbc-read-only.png"), animations: "disabled" }); + await source.getByRole("tab", { name: "Advanced", exact: true }).click(); + await source.getByRole("button", { name: "Add Property", exact: true }).click(); + await source.getByLabel("Property name", { exact: true }).fill("ssl"); + await source.getByLabel("Property value", { exact: true }).fill("true"); + await test.click(); + await expect(source.getByRole("status")).toHaveText("Succeeded: Mock JDBC database"); + const [{ source: tested, password }] = await ipcCalls(page, "db_test"); + expect(password).toBe("mock secret"); + expect(tested).toMatchObject({ + driver: "jdbc", + url, + user: "example-user", + readOnly: true, + properties: [{ name: "ssl", value: "true" }], + }); + await source.getByRole("button", { name: "OK", exact: true }).click(); + await expect(source).not.toBeVisible(); + const [{ sources }] = await ipcCalls(page, "db_save_sources"); + const [saved] = sources as Record[]; + const [{ driver }] = await ipcCalls(page, "db_save_jdbc_driver"); + expect(saved.readOnly).toBe(true); + expect(saved.jdbcDriver).toBe((driver as Record).id); + for (const key of ["jars", "className", "classpath", "exec", "password"]) expect(saved).not.toHaveProperty(key); +}); diff --git a/java/jdbc-bridge/build.py b/java/jdbc-bridge/build.py new file mode 100644 index 000000000..8b3e5f5ab --- /dev/null +++ b/java/jdbc-bridge/build.py @@ -0,0 +1,32 @@ +"""Build the committed Java 17 JDBC bridge, or run its standalone protocol tests.""" +import argparse +import os +from pathlib import Path +import subprocess +import tempfile +import zipfile + +root = Path(__file__).resolve().parent +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--test", action="store_true") +parser.add_argument("--out", type=Path, help="output JAR (with --test: the fixture driver for JDBC_FIXTURE_JAR)") +args = parser.parse_args() +java_home = os.environ.get("JAVA_HOME") +def tool(name): + return str(Path(java_home) / "bin" / name) if java_home else name + +with tempfile.TemporaryDirectory() as scratch: + classes = Path(scratch) / "classes" + classes.mkdir() + sources = sorted((root / "src").rglob("*.java")) + if args.test: + sources += sorted((root / "tests").glob("*.java")) + subprocess.run([tool("javac"), "--release", "17", "-encoding", "UTF-8", "-g:none", + "-d", classes, *sources], check=True) + if args.test: + subprocess.run([tool("java"), "-ea", "-cp", classes, "ai.openidea.jdbc.SelfTest"], check=True, timeout=45) + if not args.test or args.out: + with zipfile.ZipFile(args.out or root / "openidea-jdbc-bridge.jar", "w") as jar: + for path in sorted(classes.rglob("SelfTest*.class" if args.test else "*.class")): + entry = zipfile.ZipInfo(path.relative_to(classes).as_posix(), (2026, 1, 1, 0, 0, 0)) + jar.writestr(entry, path.read_bytes(), compress_type=zipfile.ZIP_DEFLATED) diff --git a/java/jdbc-bridge/openidea-jdbc-bridge.jar b/java/jdbc-bridge/openidea-jdbc-bridge.jar new file mode 100644 index 000000000..6a54f0f24 Binary files /dev/null and b/java/jdbc-bridge/openidea-jdbc-bridge.jar differ diff --git a/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java b/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java new file mode 100644 index 000000000..f9bf30214 --- /dev/null +++ b/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java @@ -0,0 +1,348 @@ +// The JDBC driver lives in this process only. The parent owns its lifetime and sends +// credentials over stdin. Driver console output must never enter the reply stream. +package ai.openidea.jdbc; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.sql.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicReference; + +public final class OpenIdeaJdbc { + static final int LIMIT = 16 * 1024 * 1024; + final DataInputStream input = new DataInputStream(new BufferedInputStream(System.in)); + final DataOutputStream output = new DataOutputStream(new BufferedOutputStream(System.out)); + Connection connection; + boolean catalogs; + boolean namespaceKnown; + + static void text(DataOutputStream out, String value) throws IOException { + // Leave room for the two flags and update count that terminate a result. + int available = LIMIT - out.size() - Integer.BYTES - 2 - Long.BYTES; + if (available < 0 || (value != null && value.length() > available)) + throw new IOException("JDBC result exceeds 16 MiB; select fewer or smaller values"); + if (value == null) { out.writeInt(-1); return; } + byte[] data = value.getBytes(StandardCharsets.UTF_8); + if (data.length > available) throw new IOException("JDBC result exceeds 16 MiB; select fewer or smaller values"); + out.writeInt(data.length); + out.write(data); + } + + static void header(DataOutputStream out, String... names) throws IOException { + out.writeInt(names.length); + for (String name : names) { text(out, name); text(out, "VARCHAR"); } + } + + static void row(DataOutputStream out, String... cells) throws IOException { + out.writeBoolean(true); + for (String cell : cells) text(out, cell); + } + + static void end(DataOutputStream out, boolean more, long affected) throws IOException { + out.writeBoolean(false); + out.writeBoolean(more); + out.writeLong(affected); + } + + private static class UnsupportedUrl extends SQLException {} + + private static class ReadOnlyUnavailable extends SQLException {} + + void open(List a, DataOutputStream out) throws Exception { + String className = a.get(0), url = a.get(1); + Driver driver = Class.forName(className).asSubclass(Driver.class).getConstructor().newInstance(); + var props = new Properties(); + for (int i = 5; i < a.size(); i += 2) props.setProperty(a.get(i), a.get(i+1)); + if (!a.get(2).isEmpty()) props.setProperty("user", a.get(2)); + if (!a.get(3).isEmpty()) props.setProperty("password", a.get(3)); + connection = driver.connect(url, props); + if (connection == null) throw new UnsupportedUrl(); + if (Boolean.parseBoolean(a.get(4))) { + try { connection.setReadOnly(true); } + catch (SQLException | UnsupportedOperationException e) { + throw new ReadOnlyUnavailable(); + } + } + var m = connection.getMetaData(); + header(out, "version", "quote"); + row(out, m.getDatabaseProductName() + " " + m.getDatabaseProductVersion(), m.getIdentifierQuoteString()); + } + + static String pattern(DatabaseMetaData m, String literal) throws SQLException { + String escape = m.getSearchStringEscape(); + if (escape == null || escape.isEmpty()) return literal; + return literal.replace(escape, escape + escape).replace("%", escape + "%").replace("_", escape + "_"); + } + + void schemas(DataOutputStream out) throws Exception { + var m = connection.getMetaData(); + header(out, "schema"); + Set names = new TreeSet<>(); + try (ResultSet rs = m.getSchemas()) { + while (rs.next() && names.size() < 20000) { + String s = rs.getString("TABLE_SCHEM"); + if (s != null && !s.isEmpty()) names.add(s); + } + } catch (SQLFeatureNotSupportedException ignored) {} + catalogs = names.isEmpty(); + namespaceKnown = true; + if (catalogs) { + try (ResultSet rs = m.getCatalogs()) { + while (rs.next() && names.size() < 20000) { + String s = rs.getString(1); + if (s != null && !s.isEmpty()) names.add(s); + } + } catch (SQLFeatureNotSupportedException ignored) {} + } + if (names.isEmpty()) names.add(""); + for (String s : names) row(out, s); + } + + void discoverNamespace() throws Exception { + if (!namespaceKnown) schemas(new DataOutputStream(OutputStream.nullOutputStream())); + } + + void metadata(String op, List a, DataOutputStream out) throws Exception { + discoverNamespace(); + var m = connection.getMetaData(); + String name = a.get(0); + String catalog = catalogs && !name.isEmpty() ? name : connection.getCatalog(); + String schema = catalogs || name.isEmpty() ? null : pattern(m, name); + if (op.equals("tables")) { + header(out, "name", "kind"); + try (ResultSet rs = m.getTables(catalog, schema, "%", null)) { + int n = 0; + while (rs.next() && n < 20000) { + String type = rs.getString("TABLE_TYPE").toLowerCase(Locale.ROOT); + if (!Set.of("table","base table","view","materialized view","system table","local temporary","foreign table").contains(type)) continue; + row(out, rs.getString("TABLE_NAME"), type); + n++; + } + } + } else { + header(out, "name", "type", "nullable", "default", "primary"); + String table = a.get(1); + Set keys = new HashSet<>(); + try (ResultSet rs = m.getPrimaryKeys(catalog, catalogs || name.isEmpty() ? null : name, table)) { + while (rs.next()) keys.add(rs.getString("COLUMN_NAME")); + } catch (SQLFeatureNotSupportedException ignored) {} + try (ResultSet rs = m.getColumns(catalog, schema, pattern(m, table), "%")) { + int n = 0; + while (rs.next() && n < 20000) { + if (!table.equals(rs.getString("TABLE_NAME"))) continue; + String col = rs.getString("COLUMN_NAME"); + row(out, col, rs.getString("TYPE_NAME"), rs.getInt("NULLABLE") == 0 ? "0" : "1", + rs.getString("COLUMN_DEF"), keys.contains(col) ? "1" : "0"); + n++; + } + } + } + } + + void execute(Work work, List a, DataOutputStream out, boolean tablePage) throws Exception { + long skip = Long.parseLong(a.get(1)); + int limit = Integer.parseInt(a.get(2)); + try (Statement st = connection.createStatement()) { + long window = skip + limit + 1; + if (tablePage && window > 0 && window <= Integer.MAX_VALUE) { + try { st.setMaxRows((int)window); } catch (SQLException | UnsupportedOperationException ignored) {} + } + work.begin(st); + if (!st.execute(a.get(0))) { + header(out); + end(out, false, st.getUpdateCount()); + return; + } + try (ResultSet rs = st.getResultSet()) { + var m = rs.getMetaData(); + int cols = m.getColumnCount(); + out.writeInt(cols); + for (int c = 1; c <= cols; c++) { text(out, m.getColumnLabel(c)); text(out, m.getColumnTypeName(c)); } + while (skip > 0) { + if (!rs.next()) { end(out, false, -1); return; } + skip--; + } + int n = 0; + while (n < limit && rs.next()) { + out.writeBoolean(true); + for (int c = 1; c <= cols; c++) { + int t = m.getColumnType(c); + if (t == Types.BINARY || t == Types.VARBINARY || t == Types.LONGVARBINARY || t == Types.BLOB) { + byte[] b = rs.getBytes(c); + if (b != null && b.length > (LIMIT - out.size()) / 2) throw new IOException("JDBC binary value exceeds the result limit"); + text(out, b == null ? null : "0x" + HexFormat.of().formatHex(b)); + } else { + text(out, rs.getString(c)); + } + } + n++; + } + end(out, n == limit && rs.next(), -1); + } + } + } + + // Only the query worker uses the connection. The reader may cancel its current statement. + static final class Work { + final long id; + private Statement statement; + private boolean cancelled; + + Work(long id) { this.id = id; } + + synchronized void begin(Statement st) throws SQLException { + if (cancelled) throw new SQLException("Cancelled"); + statement = st; + } + + void cancel() { + Statement st; + synchronized (this) { + cancelled = true; + st = statement; + } + if (st != null) { + try { st.cancel(); } catch (SQLException | UnsupportedOperationException ignored) {} + } + } + } + + static List readFields(DataInputStream in, int count) throws IOException { + if (count < 1 || count > 8192) throw new IOException("Invalid JDBC field count"); + int remaining = LIMIT - Long.BYTES - Integer.BYTES; + var fields = new ArrayList(count); + for (int i = 0; i < count; i++) { + remaining -= Integer.BYTES; + int n = in.readInt(); + if (n < 0 || n > remaining) throw new IOException("Invalid JDBC request length"); + byte[] bytes = in.readNBytes(n); + if (bytes.length != n) throw new EOFException(); + fields.add(new String(bytes, StandardCharsets.UTF_8)); + remaining -= n; + } + return fields; + } + + ByteArrayOutputStream reply(Work work, List a) throws IOException { + var buffer = new ByteArrayOutputStream(); + var reply = new DataOutputStream(buffer); + String op = a.remove(0); + try { + reply.writeBoolean(true); + switch (op) { + case "open" -> open(a, reply); + case "schemas" -> schemas(reply); + case "tables", "columns" -> metadata(op, a, reply); + case "namespace" -> { + header(reply, "namespace"); + String name = null; + try { + discoverNamespace(); + name = catalogs ? connection.getCatalog() : connection.getSchema(); + } catch (SQLException | AbstractMethodError ignored) {} + row(reply, name); + } + case "page" -> execute(work, a, reply, true); + case "query" -> { + if (a.size() == 3 || a.get(3).isEmpty()) { + execute(work, a, reply, false); + } else { + discoverNamespace(); + String previous = catalogs ? connection.getCatalog() : connection.getSchema(); + String wanted = a.get(3); + if (Objects.equals(previous, wanted)) { + execute(work, a, reply, false); + } else { + try { + if (catalogs) connection.setCatalog(wanted); else connection.setSchema(wanted); + if (!Objects.equals(wanted, catalogs ? connection.getCatalog() : connection.getSchema())) + throw new SQLException("The JDBC driver cannot switch to the selected schema"); + execute(work, a, reply, false); + } finally { + try { + if (catalogs) connection.setCatalog(previous); else connection.setSchema(previous); + } catch (SQLException restoreError) { + connection.close(); + throw restoreError; + } + } + } + } + } + default -> throw new IOException("Unknown JDBC operation"); + } + if (!op.equals("query") && !op.equals("page")) end(reply, false, -1); + } catch (Exception | LinkageError e) { + buffer = new ByteArrayOutputStream(); + reply = new DataOutputStream(buffer); + reply.writeBoolean(false); + if ((e instanceof ClassNotFoundException || e instanceof NoClassDefFoundError) + && e.getMessage() != null && e.getMessage().matches("[A-Za-z0-9_.$/]+")) { + text(reply, "JDBC class " + e.getMessage() + " was not found. Check the driver class and include its dependency JARs."); + } else if (e instanceof ReadOnlyUnavailable) { + text(reply, "The JDBC driver rejected Read-only. Check the driver settings and database account privileges."); + } else if (e instanceof UnsupportedUrl) { + text(reply, "The selected JDBC driver does not accept this URL"); + } else if (op.equals("open")) { + // Login exceptions may contain properties or credentials embedded in a vendor URL. + String state = e instanceof SQLException ? ((SQLException)e).getSQLState() : null; + text(reply, "JDBC connection failed (" + e.getClass().getSimpleName() + + (state == null ? "" : ", SQLState " + state) + "). Check driver files, class, URL and credentials."); + } else { + text(reply, e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); + } + } + return buffer; + } + + synchronized void send(ByteArrayOutputStream reply) throws IOException { + output.writeInt(reply == null ? 0 : reply.size()); + if (reply != null) reply.writeTo(output); + output.flush(); + } + + void run() throws IOException { + System.setOut(System.err); + var active = new AtomicReference(); + var worker = Executors.newSingleThreadExecutor(r -> { + var thread = new Thread(r, "jdbc-session"); + thread.setDaemon(true); + return thread; + }); + try { + for (;;) { + long id; + try { id = input.readLong(); } catch (EOFException eof) { return; } + int count = input.readInt(); + if (count == 0) { + var work = active.get(); + if (work != null && work.id == id) work.cancel(); + send(null); // Acknowledge even a cancel that raced with a completed request. + continue; + } + var fields = readFields(input, count); + var work = new Work(id); + if (!active.compareAndSet(null, work)) throw new IOException("Overlapping JDBC requests"); + worker.execute(() -> { + try { + var result = reply(work, fields); + active.compareAndSet(work, null); + send(result); + } catch (Throwable fatal) { + // Without a complete frame the parent must discard this session. + Runtime.getRuntime().halt(1); + } + }); + } + } finally { + worker.shutdownNow(); + } + } + + public static void main(String[] args) throws Exception { + var bridge = new OpenIdeaJdbc(); + try { bridge.run(); } + finally { if (bridge.connection != null) bridge.connection.close(); } + } +} diff --git a/java/jdbc-bridge/tests/SelfTest.java b/java/jdbc-bridge/tests/SelfTest.java new file mode 100644 index 000000000..9f8dfeb5d --- /dev/null +++ b/java/jdbc-bridge/tests/SelfTest.java @@ -0,0 +1,129 @@ +package ai.openidea.jdbc; + +import java.io.*; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.*; +import java.util.*; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.logging.Logger; + +/** Drives the bridge over its actual pipes with a deterministic JDBC driver. */ +public class SelfTest { + public static class Fixture implements Driver { + private boolean readonly; + private int changes; + private Path started; + + @SuppressWarnings("unchecked") + static T proxy(Class type, java.lang.reflect.InvocationHandler handler) { + return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, handler); + } + + public Connection connect(String url, Properties props) { + String path = url.substring("jdbc:fixture:".length()); + started = path.isEmpty() ? null : Path.of(path); + var meta = proxy(DatabaseMetaData.class, (p, m, a) -> switch (m.getName()) { + case "getDatabaseProductName" -> "Fixture"; + case "getDatabaseProductVersion" -> "1"; + case "getIdentifierQuoteString" -> "\""; + default -> throw new SQLFeatureNotSupportedException(); + }); + return proxy(Connection.class, (p, m, a) -> switch (m.getName()) { + case "setReadOnly" -> { readonly = (boolean) a[0]; yield null; } + case "getMetaData" -> meta; + case "close" -> null; + case "createStatement" -> statement(); + default -> throw new SQLFeatureNotSupportedException(); + }); + } + + Statement statement() { + var stop = new CountDownLatch(1); + return proxy(Statement.class, (p, m, a) -> switch (m.getName()) { + case "execute" -> { + String sql = (String) a[0]; + if (sql.equals("wait") || sql.equals("ignore cancel")) { + if (started != null) java.nio.file.Files.writeString(started, "started"); + System.err.println("statement started"); + if (sql.equals("ignore cancel")) Thread.sleep(60_000); + if (!stop.await(20, TimeUnit.SECONDS)) throw new SQLException("test timed out"); + throw new SQLException("statement cancelled"); + } + if (sql.equals("write") && readonly) throw new SQLException("read-only"); + changes++; + yield false; + } + case "cancel" -> { stop.countDown(); yield null; } + case "getUpdateCount" -> changes; + case "close" -> null; + default -> throw new SQLFeatureNotSupportedException(); + }); + } + public boolean acceptsURL(String url) { return true; } + public DriverPropertyInfo[] getPropertyInfo(String url, Properties p) { return new DriverPropertyInfo[0]; } + public int getMajorVersion() { return 1; } + public int getMinorVersion() { return 0; } + public boolean jdbcCompliant() { return false; } + public Logger getParentLogger() { return Logger.getGlobal(); } + } + + static void send(DataOutputStream out, long id, String... fields) throws IOException { + out.writeLong(id); + out.writeInt(fields.length); + for (String s : fields) { + byte[] b = s.getBytes(StandardCharsets.UTF_8); + out.writeInt(b.length); + out.write(b); + } + out.flush(); + } + + static byte[] reply(DataInputStream in) throws IOException { + int size = in.readInt(); + assert size >= 0 && size <= OpenIdeaJdbc.LIMIT; + byte[] bytes = new byte[size]; + in.readFully(bytes); + return bytes; + } + + public static void main(String[] args) throws Exception { + var boundary = new DataOutputStream(OutputStream.nullOutputStream()); + OpenIdeaJdbc.text(boundary, "x".repeat(OpenIdeaJdbc.LIMIT - 14)); + OpenIdeaJdbc.end(boundary, false, -1); + assert boundary.size() == OpenIdeaJdbc.LIMIT; + try { + OpenIdeaJdbc.text(boundary, ""); + throw new AssertionError("Oversized reply accepted"); + } catch (IOException expected) {} + var java = Path.of(System.getProperty("java.home"), "bin", "java").toString(); + var child = new ProcessBuilder(java, "-cp", System.getProperty("java.class.path"), + OpenIdeaJdbc.class.getName()).start(); + try (var out = new DataOutputStream(child.getOutputStream()); + var in = new DataInputStream(child.getInputStream()); + var log = child.errorReader()) { + send(out, 1, "open", Fixture.class.getName(), "jdbc:fixture:", "", "", "true"); + assert reply(in)[0] == 1; + send(out, 2, "query", "write", "0", "2"); + assert reply(in)[0] == 0; + send(out, 3, "query", "first", "0", "2"); + assert reply(in)[0] == 1; + send(out, 4, "query", "wait", "0", "2"); + assert log.lines().anyMatch("statement started"::equals); + send(out, 3); // A late Cancel for the previous request cannot stop this one. + assert reply(in).length == 0; + send(out, 4); + var first = reply(in); + var second = reply(in); + assert (first.length == 0) != (second.length == 0); + assert (first.length == 0 ? second : first)[0] == 0; + send(out, 5, "query", "after cancel", "0", "2"); + var result = reply(in); + assert result[0] == 1 && result[result.length - 1] == 2; + } finally { + child.destroyForcibly().waitFor(); + } + } +} diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 5a57b1655..960b06007 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -89,6 +89,7 @@ coverage_import always project_host bin coverage_prepare trusted project_host bindings async cucumber_sources trusted desktop bindings async db_apply_edits trusted project_host bindings async +db_approve_jdbc_source trusted project_host bindings sync db_completion trusted project_host bindings async db_connect trusted project_host bindings async db_connected trusted project_host bindings sync @@ -106,10 +107,14 @@ db_explain trusted project_host bin db_export_file always desktop bindings async db_finish_transaction trusted project_host bindings async db_history trusted project_host bindings async +db_jdbc_driver_classes trusted project_host bindings async +db_jdbc_drivers trusted project_host bindings sync db_object_ddl trusted project_host bindings async db_remove_history trusted project_host bindings async +db_remove_jdbc_driver trusted project_host bindings sync db_retain_catalog trusted project_host bindings async db_run_tool trusted desktop bindings async +db_save_jdbc_driver trusted project_host bindings sync db_save_sources trusted project_host bindings async db_saved_catalog trusted project_host bindings async db_schema_objects trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 4d11b5a8c..d562a2059 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -286,6 +286,7 @@ export const commands = { /** Cucumber feature files and step definition files, for step navigation. */ cucumberSources: () => typedError(__TAURI_INVOKE("cucumber_sources")), dbApplyEdits: (id: string, schema: string, table: string, edits: DbRowEdit[]) => typedError(__TAURI_INVOKE("db_apply_edits", { id, schema, table, edits })), + dbApproveJdbcSource: (source: DataSource_Deserialize) => typedError(__TAURI_INVOKE("db_approve_jdbc_source", { source })), dbCompletion: (id: string) => typedError(__TAURI_INVOKE("db_completion", { id })), dbConnect: (id: string) => typedError(__TAURI_INVOKE("db_connect", { id })), dbConnected: () => typedError(__TAURI_INVOKE("db_connected")), @@ -310,14 +311,18 @@ export const commands = { dbExportFile: (path: string, text: string) => typedError(__TAURI_INVOKE("db_export_file", { path, text })), dbFinishTransaction: (id: string, commit: boolean) => typedError(__TAURI_INVOKE("db_finish_transaction", { id, commit })), dbHistory: (id: string) => typedError(__TAURI_INVOKE("db_history", { id })), + dbJdbcDriverClasses: (jars: string[]) => typedError(__TAURI_INVOKE("db_jdbc_driver_classes", { jars })), + dbJdbcDrivers: () => typedError(__TAURI_INVOKE("db_jdbc_drivers")), dbObjectDdl: (id: string, schema: string, kind: DbObjectKind, name: string) => typedError(__TAURI_INVOKE("db_object_ddl", { id, schema, kind, name })), dbRemoveHistory: (id: string, texts: string[] | null) => typedError(__TAURI_INVOKE("db_remove_history", { id, texts })), + dbRemoveJdbcDriver: (id: string) => typedError(__TAURI_INVOKE("db_remove_jdbc_driver", { id })), dbRetainCatalog: (id: string, databases: string[]) => typedError(__TAURI_INVOKE("db_retain_catalog", { id, databases })), /** * Runs `job` against target `id` and streams the tool's output; returns its exit code. Stays * in the desktop shell like [`db_export_file`]: the paths in `job` are local. */ dbRunTool: (request: RequestId, id: string, executable: string, job: DbToolJob, onOutput: Channel) => typedError(__TAURI_INVOKE("db_run_tool", { request, id, executable, job, onOutput })), + dbSaveJdbcDriver: (driver: DbJdbcDriver) => typedError(__TAURI_INVOKE("db_save_jdbc_driver", { driver })), dbSaveSources: (sources: DataSource_Deserialize[]) => typedError(__TAURI_INVOKE("db_save_sources", { sources })), dbSavedCatalog: (id: string) => typedError<{ databases?: DbCatalogDatabase[], @@ -4113,6 +4118,8 @@ export type DataSource_Deserialize = { id?: string, name?: string, driver?: DbDriver, + /** An app-wide driver profile id; classpaths never come from a project. */ + jdbcDriver?: string, host?: string, port?: number | null, database?: string, @@ -4157,6 +4164,8 @@ export type DataSource_Serialize = { id: string, name: string, driver: DbDriver, + /** An app-wide driver profile id; classpaths never come from a project. */ + jdbcDriver?: string, host: string, port: number | null, database: string, @@ -4288,7 +4297,7 @@ export type DbDriver = "sqlite" | "postgres" | /** Microsoft SQL Server. */ "sqlServer" | "clickhouse" | /** Oracle Database (pure-Rust thin driver, no client library). */ -"oracle" | "snowflake"; +"oracle" | "snowflake" | "jdbc"; export type DbDumpContent = "all" | "schemaOnly" | "dataOnly"; @@ -4358,6 +4367,14 @@ export type DbIntrospection = { objectFilter?: string, }; +export type DbJdbcDriver = { + id: string, + name: string, + jars: string[], + className: string, + urlTemplate: string, +}; + export type DbMysqlOptions = { /** Empty: the databases the dump names. */ database: string, diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css index aab7c068e..6b3716955 100644 --- a/src/features/database/Database.module.css +++ b/src/features/database/Database.module.css @@ -370,6 +370,46 @@ font-size: var(--fs-small); color: var(--fg-muted); } +.jdbcJars { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: var(--space-2); +} +.jdbcJars ul { + width: 100%; + max-height: 160px; + overflow: auto; + margin: 0; + padding: 0; + list-style: none; +} +.jdbcJars li { + display: flex; + align-items: center; + gap: var(--space-2); +} +.jdbcJars li span { + flex: 1; + min-width: 0; + overflow-wrap: anywhere; +} +.jdbcDetails { + grid-column: 1 / -1; + margin: 0; +} +.jdbcDetails dt { + margin-top: var(--space-2); + color: var(--fg-secondary); +} +.jdbcDetails dd { + margin: var(--space-1) 0; + overflow-wrap: anywhere; +} +.jdbcDetails ul { + margin: 0; + padding-left: var(--space-4); +} .formFull { grid-column: 1 / -1; } @@ -1479,3 +1519,7 @@ .dumpError { color: var(--danger); } + +.jdbcJarPath { + overflow-wrap: anywhere; +} diff --git a/src/features/database/JdbcDriverProfiles.tsx b/src/features/database/JdbcDriverProfiles.tsx new file mode 100644 index 000000000..af00b342a --- /dev/null +++ b/src/features/database/JdbcDriverProfiles.tsx @@ -0,0 +1,345 @@ +import { useEffect, useState } from "react"; +import { call, commands, type DbJdbcDriver } from "@/platform/ipc"; +import { useTx } from "@/platform/i18n"; +import { Button, Dialog, IconButton, Input, Select, T } from "@/ui"; +import { baseName } from "./dumpTools"; +import { newSourceId } from "./model"; +import styles from "./Database.module.css"; + +export function useJdbcDrivers(enabled: boolean) { + const [drivers, setDrivers] = useState(null); + const [error, setError] = useState(null); + const [attempt, setAttempt] = useState(0); + const [wasEnabled, setWasEnabled] = useState(enabled); + if (wasEnabled !== enabled) { + setWasEnabled(enabled); + setDrivers(null); + setError(null); + } + useEffect(() => { + if (!enabled) return; + let active = true; + void call(commands.dbJdbcDrivers()).then( + (value) => { + if (active) setDrivers(value); + }, + (e: unknown) => { + if (active) setError(e instanceof Error ? e.message : String(e)); + }, + ); + return () => { + active = false; + }; + }, [enabled, attempt]); + const retry = () => { + setDrivers(null); + setError(null); + setAttempt((n) => n + 1); + }; + return { drivers, setDrivers, error, retry }; +} + +const blankDriver = (): DbJdbcDriver => ({ id: newSourceId(), name: "", jars: [], className: "", urlTemplate: "" }); + +export function JdbcDriverProfiles({ + drivers, + selected, + onSave, + onUse, + onRemove, + onClose, +}: { + drivers: DbJdbcDriver[]; + selected: string; + onSave: (driver: DbJdbcDriver) => void; + onUse?: (driver: DbJdbcDriver) => void; + onRemove: (id: string) => void; + onClose: () => void; +}) { + const tx = useTx(); + const [selection, setSelection] = useState( + drivers.some((d) => d.id === selected) ? selected : (drivers[0]?.id ?? ""), + ); + const [draft, setDraft] = useState(null); + const [confirm, setConfirm] = useState<"trust" | "delete" | null>(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [classes, setClasses] = useState([]); + const current = drivers.find((d) => d.id === selection); + const name = current?.name ?? ""; + const set = (patch: Partial) => setDraft((d) => d && { ...d, ...patch }); + const classValid = + !!draft && /^[\p{L}_$][\p{L}\p{N}_$]*(?:\.[\p{L}_$][\p{L}\p{N}_$]*)+$/u.test(draft.className.trim()); + const templateValid = !draft?.urlTemplate || /^jdbc:[^\s:]+:[^\r\n]*$/.test(draft.urlTemplate); + const valid = !!draft?.name.trim() && !!draft.jars.length && classValid && templateValid; + const edit = (driver: DbJdbcDriver) => { + setError(null); + setClasses([]); + setDraft({ ...driver, jars: [...driver.jars] }); + }; + + const pickJars = async () => { + setBusy(true); + setError(null); + try { + const { open } = await import("@/platform/dialog"); + const files = await open({ + title: tx("Choose JDBC Driver and Dependency JARs"), + multiple: true, + directory: false, + filters: [{ name: tx("Java archives"), extensions: ["jar"] }], + }); + if (files && draft) { + const jars = [...new Set([...draft.jars, ...files])]; + set({ jars }); + const names = await call(commands.dbJdbcDriverClasses(jars)); + setClasses(names); + if (!draft.className && names.length) set({ className: names[0] }); + } + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + const save = async () => { + if (!draft || !valid || busy) return; + setBusy(true); + setError(null); + const driver = { ...draft, name: draft.name.trim(), className: draft.className.trim() }; + try { + await call(commands.dbSaveJdbcDriver(driver)); + onSave(driver); + setSelection(driver.id); + setDraft(null); + setConfirm(null); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + setConfirm(null); + } finally { + setBusy(false); + } + }; + + const remove = async () => { + if (!current || busy) return; + setBusy(true); + setError(null); + try { + await call(commands.dbRemoveJdbcDriver(current.id)); + onRemove(current.id); + setSelection(drivers.find((d) => d.id !== current.id)?.id ?? ""); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setConfirm(null); + setBusy(false); + } + }; + + return ( + <> + d.id === draft.id) + ? "Edit JDBC Driver" + : "Add JDBC Driver" + : "JDBC Driver Profiles" + } + onClose={() => { + if (busy) return; + if (draft) setDraft(null); + else onClose(); + }} + width={640} + buttons={ + draft + ? [ + { label: "Cancel", role: "cancel", disabled: busy }, + { label: "Save", role: "default", disabled: busy || !valid, onClick: () => setConfirm("trust") }, + ] + : [ + { label: "Close", role: "cancel", disabled: busy }, + ...(onUse && current + ? [{ label: "Use Driver", role: "default" as const, onClick: () => onUse(current) }] + : []), + ] + } + > +
+

+ Driver profiles are stored locally and shared by all projects. +

+ {draft ? ( + <> + + set({ name: e.target.value })} + /> + + Driver and dependency JARs: + +
+
    + {draft.jars.map((jar) => ( +
  • + {baseName(jar)} + { + setClasses([]); + set({ jars: draft.jars.filter((path) => path !== jar) }); + }} + /> +
  • + ))} +
+ +
+ + set({ className: e.target.value })} + /> + + + + {classes.map((name) => ( + + Select a class declared by the JARs, or enter its fully qualified name. + + + set({ urlTemplate: e.target.value })} + /> + + + {"Use {host}, {port}, {database} or {file} for fields on the connection form."} + + + ) : ( + <> + + JDBC driver profile: + + set({ host: e.target.value })} - /> - - set({ port: parsePort(e.target.value) })} + aria-label="JDBC driver profile" + value={s.jdbcDriver ?? ""} + disabled={!jdbcProfiles.drivers} + onChange={(id) => chooseProfile(jdbcProfiles.drivers?.find((d) => d.id === id))} + options={[ + { value: "", label: "Choose a JDBC driver profile" }, + ...(jdbcProfiles.drivers ?? []).map((d) => ({ value: d.id, label: d.name, verbatim: true })), + ...(s.jdbcDriver && !jdbcProfile + ? [{ value: s.jdbcDriver, label: tx`${s.jdbcDriver} (missing)` }] + : []), + ]} /> +
+ {fromTemplate && + templateFields.map((key) => ( + + +
+ + set({ [key]: key === "port" ? parsePort(e.target.value) : e.target.value, url: template }) + } + /> + {key === "file" && ( + + )} +
+
+ ))} + {!fromTemplate && templateFields.length > 0 && ( + <> + + + + )} + {jdbcProfiles.error ? ( +
+ {jdbcProfiles.error}{" "} + +
+ ) : !jdbcProfiles.drivers ? ( + + Loading JDBC driver profiles… + + ) : s.jdbcDriver && !jdbcProfile ? ( + + The JDBC driver profile is missing. Select or add a profile before connecting. + + ) : null} + + ) : ( + <> + + Connection type: + +
+ + +
+ {!urlOnly && ( + <> + +
+ set({ host: e.target.value })} + /> + + set({ port: parsePort(e.target.value) })} + /> +
+ + )} )} {sshOn && ( @@ -676,7 +859,7 @@ export function SourceDialog({ label="Save password" /> - {!urlOnly && ( + {!urlOnly && !jdbc && ( <>