diff --git a/crates/ide-db/src/jdbc/ducklake.rs b/crates/ide-db/src/jdbc/ducklake.rs new file mode 100644 index 0000000000..1f3e00f23d --- /dev/null +++ b/crates/ide-db/src/jdbc/ducklake.rs @@ -0,0 +1,103 @@ +use super::{DbJdbcDriver, JdbcPool}; +use crate::source::{DUCKDB_URL, duck_lake_path}; +use crate::{DataSource, DbDuckLake, DbDuckLakeKind, DbManager, Pool}; +use ide_core::{IdeError, IdeResult}; + +const DUCKDB_CLASS: &str = "org.duckdb.DuckDBDriver"; + +impl DbManager { + pub fn approve_ducklake_source(&self, source: &DataSource) -> IdeResult<()> { + if source.duck_lake.is_none() { + return Err(IdeError::invalid("Expected a DuckLake data source")); + } + source.validate_duck_lake()?; + self.duck_lake_driver(&source.jdbc_driver)?.validate()?; + if source.global { + return Ok(()); + } + self.record_jdbc_approval(source) + } + + fn duck_lake_driver(&self, id: &str) -> IdeResult { + let driver = self.jdbc_driver_by_id(id)?; + driver.require_vendor("duckdb")?; + if driver.class_name != DUCKDB_CLASS { + return Err(IdeError::invalid("Select a DuckDB driver profile with the official DuckDB JDBC driver class")); + } + Ok(driver) + } + + /// Creates a lake in a new directory through a separate, disposable JDBC session. + pub async fn create_ducklake(&self, jdbc_driver: &str, directory: &str) -> IdeResult<()> { + duck_lake_path(directory, false)?; + let driver = self.duck_lake_driver(jdbc_driver)?; + let fields = duck_lake_fields("create", directory.to_owned(), ""); + let pool = JdbcPool::open(driver, self.jdbc_registry()?.with_file_name("jdbc"), fields).await?; + pool.close().await; + Ok(()) + } + + pub(super) async fn open_ducklake(&self, source: &DataSource, lake: &DbDuckLake, testing: bool) -> IdeResult { + source.validate_duck_lake()?; + self.check_jdbc_project_approval(source, testing)?; + let driver = self.duck_lake_driver(&source.jdbc_driver)?; + let cache = self.jdbc_registry()?.with_file_name("jdbc"); + let (mode, value) = match lake.kind { + DbDuckLakeKind::Secret => ("secret", lake.value.clone()), + DbDuckLakeKind::File => { + let path = self.root.join(&lake.value); + let value = path.to_str().ok_or_else(|| IdeError::invalid("Invalid DuckLake catalog file path"))?; + duck_lake_path(value, false)?; + ("file", value.to_owned()) + } + }; + let fields = duck_lake_fields(mode, value, lake.data_path.as_deref().unwrap_or_default()); + JdbcPool::open(driver, cache, fields).await.map(Box::new).map(Pool::Jdbc) + } +} + +fn duck_lake_fields(mode: &str, value: String, data_path: &str) -> Vec { + vec![ + "openDuckLake".into(), + DUCKDB_CLASS.into(), + DUCKDB_URL.into(), + String::new(), + String::new(), + (mode != "create").to_string(), + mode.into(), + value, + data_path.to_owned(), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn ordinary_jdbc_rejects_a_ducklake_even_with_a_file_url() { + let source = DataSource { + driver: crate::DbDriver::Jdbc, + url: "jdbc:duckdb:existing.duckdb".into(), + duck_lake: Some(DbDuckLake { + kind: DbDuckLakeKind::File, + value: "catalog.ducklake".into(), + data_path: None, + }), + ..Default::default() + }; + let driver = DbJdbcDriver { + id: "duckdb".into(), + name: "DuckDB".into(), + vendor: Some("duckdb".into()), + jars: vec![], + class_name: DUCKDB_CLASS.into(), + url_template: DUCKDB_URL.into(), + }; + let error = JdbcPool::connect(&source, None, driver, Default::default()) + .await + .err() + .expect("ordinary JDBC must reject DuckLake fields before opening a connection"); + assert_eq!(error.message, "DuckLake catalogs require a DuckLake connection"); + } +} diff --git a/crates/ide-db/src/jdbc/mod.rs b/crates/ide-db/src/jdbc/mod.rs index 2ac936c777..a7017d556d 100644 --- a/crates/ide-db/src/jdbc/mod.rs +++ b/crates/ide-db/src/jdbc/mod.rs @@ -15,6 +15,7 @@ use tokio::sync::Mutex; use tokio::time::timeout; mod bridge; +mod ducklake; use bridge::Bridge; @@ -79,6 +80,13 @@ pub fn jdbc_driver_classes(jars: &[String]) -> IdeResult> { } impl DbJdbcDriver { + fn require_vendor(&self, vendor: &str) -> IdeResult<()> { + if self.vendor.as_deref() != Some(vendor) { + return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type")); + } + Ok(()) + } + fn validate(&self) -> IdeResult<()> { if self.id.is_empty() || self.name.trim().is_empty() @@ -138,6 +146,30 @@ impl DbManager { self.update_jdbc_driver(id, None) } + fn record_jdbc_approval(&self, source: &DataSource) -> IdeResult<()> { + let (path, fingerprint) = self.jdbc_approval(source)?; + persist_local(&path, fingerprint.as_bytes()) + } + + fn jdbc_driver_by_id(&self, id: &str) -> IdeResult { + self.jdbc_drivers()? + .into_iter() + .find(|d| d.id == id) + .ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile")) + } + + fn check_jdbc_project_approval(&self, source: &DataSource, testing: bool) -> IdeResult<()> { + 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", + )); + } + } + Ok(()) + } + 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()))?; @@ -150,7 +182,10 @@ impl DbManager { &source.options, )) .map_err(|e| IdeError::internal(e.to_string()))?; - if self.jdbc_password_isolated(source) { + if let Some(lake) = &source.duck_lake { + settings.extend_from_slice(b"\0ducklake\0"); + serde_json::to_writer(&mut settings, lake).map_err(|e| IdeError::internal(e.to_string()))?; + } else if self.jdbc_password_isolated(source) { settings.extend_from_slice(b"\0jdbc-password"); } Ok(( @@ -164,8 +199,10 @@ impl DbManager { 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()) + if source.duck_lake.is_some() { + return self.approve_ducklake_source(source); + } + self.record_jdbc_approval(source) } pub(crate) async fn open_pool( @@ -174,27 +211,19 @@ impl DbManager { password: Option<&str>, testing: bool, ) -> IdeResult { + if let Some(lake) = &source.duck_lake { + return self.open_ducklake(source, lake, testing).await; + } 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"))?; - if !source.vendor.is_empty() && driver.vendor.as_deref() != Some(source.vendor.as_str()) { - return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type")); + self.check_jdbc_project_approval(source, testing)?; + let driver = self.jdbc_driver_by_id(&source.jdbc_driver)?; + if !source.vendor.is_empty() { + driver.require_vendor(&source.vendor)?; } JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc")) .await @@ -277,10 +306,12 @@ impl JdbcPool { driver: DbJdbcDriver, cache: PathBuf, ) -> IdeResult { - driver.validate()?; + if source.duck_lake.is_some() { + return Err(IdeError::invalid("DuckLake catalogs require a DuckLake connection")); + } let mut fields = vec![ "open".to_string(), - driver.class_name, + driver.class_name.clone(), source.url.clone(), source.user.clone(), password.unwrap_or_default().to_owned(), @@ -292,6 +323,11 @@ impl JdbcPool { } fields.extend([p.name.clone(), p.value.clone()]); } + Self::open(driver, cache, fields).await + } + + async fn open(driver: DbJdbcDriver, cache: PathBuf, fields: Vec) -> IdeResult { + driver.validate()?; let bridge = tokio::task::spawn_blocking(move || Bridge::start(&cache, &driver.jars)) .await .map_err(|e| IdeError::internal(e.to_string()))??; @@ -306,7 +342,7 @@ impl JdbcPool { bridge: Arc::new(bridge), service: Session::new(0), consoles: Default::default(), - shared_connection: private_database_url(&source.url), + shared_connection: private_database_url(&fields[2]), version: metadata.next().flatten().unwrap_or_else(|| "Connected".into()), identifier_quote: metadata.next().flatten().unwrap_or_default().trim().into(), }) @@ -748,7 +784,9 @@ mod tests { assert!(catalogs.contains(&vec![Some("memory".into()), Some("1".into())])); assert!(catalogs.contains(&vec![Some("first".into()), Some("0".into())])); assert!(catalogs.contains(&vec![Some(archive.into()), Some("0".into())])); - let schemas = pool.metadata(&["schemas", archive]).await?; + let mut schemas = pool.metadata(&["schemas", archive]).await?; + // DuckDB JDBC 1.1.3 also lists these system schemas for attached catalogs. + schemas.retain(|row| !matches!(row[0].as_deref(), Some("information_schema" | "pg_catalog"))); assert_eq!(schemas, ["main", "qaSimilar", "qa_%"].map(|schema| vec![Some(schema.into())])); let tables = pool.metadata(&["tables", "qa_%", archive]).await?; assert_eq!(tables.len(), 1); diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index a4331f60eb..0e990585ea 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -31,8 +31,9 @@ pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell}; pub use history::HistoryEntry; pub use plan::{PlanNode, PlanProperty}; pub use source::{ - DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection, - DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange, + DataSource, DbColor, DbDriver, DbDuckLake, DbDuckLakeKind, DbExternalTunnel, DbIntrospection, DbOptions, + DbProperty, DbSchemaSelection, DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, + DbVisibilityChange, }; pub use sql::{CellValue, DbRowEdit, SortKey}; @@ -544,6 +545,13 @@ pub fn split_target(target: &str) -> (&str, Option<&str>) { } } +fn reject_duck_lake_password(password: Option<&str>) -> IdeResult<()> { + if password.is_some_and(|p| !p.is_empty()) { + return Err(IdeError::invalid("DuckLake uses a catalog file or named secret without a JDBC or SSH password")); + } + Ok(()) +} + /// Says which leg failed when the database is unreachable from the SSH host. fn through_tunnel(e: IdeError, source: &DataSource, via: Option<&str>) -> IdeError { let Some(via) = via.filter(|_| e.kind == ErrorKind::Io) else { return e }; @@ -697,13 +705,16 @@ impl DbManager { /// Saves the data source list, preserving connections when only visibility rules change. /// Global ones (`global`) go to the app-wide list, the others to the project's. pub async fn save_sources(&self, mut sources: Vec) -> IdeResult<()> { + for source in &sources { + source.validate_duck_lake()?; + } if sources.iter().any(|s| s.global && s.plugin_owner.is_some()) { return Err(IdeError::invalid("plugin-owned data sources must stay project-scoped")); } let old = { let _guard = plugin::EDIT.lock(); let old = self.sources().unwrap_or_default(); - for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc) { + for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc && s.duck_lake.is_none()) { // Retain the credential scope even when URL-only settings supplied the old authenticator. if let Some(settings) = old.iter().find(|s| s.id == source.id).and_then(Self::non_password_snowflake) { source.snowflake = Some(settings); @@ -752,7 +763,7 @@ impl DbManager { } } // Made global or project-level: its saved passwords move along. - Some(n) if n.global != o.global => { + Some(n) if n.global != o.global && n.duck_lake.is_none() && o.duck_lake.is_none() => { for k in &keys { if let Some(p) = self.store_of(&o).get(k) { self.store_of(n).set(k, &p)?; @@ -834,6 +845,9 @@ impl DbManager { /// the data source saves passwords (`None` forgets it). pub async fn set_password(&self, id: &str, password: Option, save: bool) -> IdeResult<()> { let source = self.sources()?.into_iter().find(|s| s.id == id); + if source.as_ref().is_some_and(|s| s.duck_lake.is_some()) { + return reject_duck_lake_password(password.as_deref()); + } let (store, key) = match source.as_ref() { Some(source) => (self.store_of(source), self.password_key(source)), None => (&self.saved_passwords, id.to_owned()), @@ -844,7 +858,11 @@ impl DbManager { /// [`DbManager::set_password`] for the SSH password / key passphrase. /// A data source using an SSH configuration sets that configuration's secret. pub async fn set_ssh_secret(&self, id: &str, secret: Option, save: bool) -> IdeResult<()> { - let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config); + let source = self.sources()?.into_iter().find(|s| s.id == id); + if source.as_ref().is_some_and(|s| s.duck_lake.is_some()) { + return reject_duck_lake_password(secret.as_deref()); + } + let config = source.and_then(|s| s.ssh).map(|s| s.config); if let Some(c) = config.filter(|c| !c.trim().is_empty()) { let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save); return self.ssh.set_secret(&c, secret, save); @@ -889,6 +907,9 @@ impl DbManager { } async fn password(&self, source: &DataSource) -> Option { + if source.duck_lake.is_some() { + return None; + } match self .secret(source, self.password_key(source), source.driver != DbDriver::Sqlite && source.save_password) .await @@ -997,6 +1018,10 @@ impl DbManager { purpose: route::RouteUse, ) -> IdeResult { let source = &source.resolved()?; + if source.duck_lake.is_some() { + reject_duck_lake_password(password.as_deref())?; + reject_duck_lake_password(ssh_secret.as_deref())?; + } let password = match password { Some(p) => Some(p), None => self.password(source).await, diff --git a/crates/ide-db/src/source.rs b/crates/ide-db/src/source.rs index 88cb72ebe3..570872e195 100644 --- a/crates/ide-db/src/source.rs +++ b/crates/ide-db/src/source.rs @@ -11,6 +11,7 @@ use std::collections::{BTreeMap, HashSet}; use std::path::Path; pub(crate) const FILE: &str = "data-sources.toml"; +pub(crate) const DUCKDB_URL: &str = "jdbc:duckdb:"; pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml"; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)] @@ -306,6 +307,25 @@ pub struct DbExternalTunnel { pub arguments: Vec, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum DbDuckLakeKind { + File, + Secret, +} + +/// How to open an existing DuckLake catalog read-only through DuckDB. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DbDuckLake { + pub kind: DbDuckLakeKind, + /// A local catalog file or an existing DuckDB secret name. + pub value: String, + /// An existing local data directory overriding the catalog's data path. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub data_path: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase", default)] pub struct DataSource { @@ -346,6 +366,8 @@ pub struct DataSource { pub properties: Vec, /// Snowflake settings (`None`: not a Snowflake data source, or all defaults). pub snowflake: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub duck_lake: Option, /// Stored app-wide and listed in every project. Implied by the file it is read from, /// so not written to it. pub global: bool, @@ -386,6 +408,7 @@ impl Default for DataSource { introspection: DbIntrospection::default(), properties: Vec::new(), snowflake: None, + duck_lake: None, global: false, plugin_owner: None, plugin_source_id: None, @@ -513,7 +536,69 @@ pub fn parse_url(raw: &str) -> IdeResult { Ok(parsed) } +pub(crate) fn duck_lake_path(value: &str, relative: bool) -> IdeResult<&Path> { + let path = Path::new(value); + if value.trim().is_empty() + || value.contains(['\0', '\r', '\n']) + || value.starts_with("//") + || value.starts_with('\\') + || (!path.is_absolute() && (!relative || value.starts_with('/') || value.contains(':'))) + { + return Err(IdeError::invalid("Choose a local DuckLake path on the database host")); + } + Ok(path) +} + impl DataSource { + pub(crate) fn validate_duck_lake(&self) -> IdeResult<()> { + let Some(lake) = &self.duck_lake else { return Ok(()) }; + if self.driver != DbDriver::Jdbc + || self.vendor != "duckdb" + || self.url != DUCKDB_URL + || self.url_only + || !self.read_only + || self.plugin_owner.is_some() + { + return Err(IdeError::invalid("Existing DuckLake catalogs require a read-only DuckDB JDBC data source")); + } + if !self.user.is_empty() + || self.save_password + || self.ssh.is_some() + || self.external_tunnel.is_some() + || !self.properties.is_empty() + { + return Err(IdeError::invalid( + "DuckLake uses its catalog file or named secret without JDBC credentials, properties or tunnels", + )); + } + if self.options.transaction != DbTxMode::Auto + || !self.options.default_schema.is_empty() + || !self.options.time_zone.is_empty() + || !self.options.startup_script.is_empty() + { + return Err(IdeError::invalid("DuckLake does not use JDBC session overrides")); + } + match lake.kind { + DbDuckLakeKind::File => { + duck_lake_path(&lake.value, true)?; + } + DbDuckLakeKind::Secret => { + let mut chars = lake.value.bytes(); + if !chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == b'_') + || !chars.all(|c| c.is_ascii_alphanumeric() || c == b'_') + { + return Err(IdeError::invalid( + "Enter an existing DuckLake secret name using letters, digits or underscores", + )); + } + } + } + if let Some(path) = lake.data_path.as_deref().filter(|path| !path.is_empty()) { + duck_lake_path(path, false)?; + } + Ok(()) + } + pub(crate) fn select_database(&mut self, database: Option<&str>) { if let Some(db) = database { // The configured schema belongs to the configured database. @@ -536,6 +621,7 @@ 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 { + self.validate_duck_lake()?; if self.driver == DbDriver::Jdbc { if !self.url.starts_with("jdbc:") { return Err(IdeError::invalid("Enter a JDBC URL starting with jdbc:")); diff --git a/crates/ide-db/tests/jdbc.rs b/crates/ide-db/tests/jdbc.rs index bd4ed70b3c..b0f7b56eb1 100644 --- a/crates/ide-db/tests/jdbc.rs +++ b/crates/ide-db/tests/jdbc.rs @@ -1,5 +1,7 @@ use ide_core::{CancellationToken, IdeResult}; -use ide_db::{ConsoleId, DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey}; +use ide_db::{ + ConsoleId, DataSource, DbDriver, DbDuckLake, DbDuckLakeKind, DbJdbcDriver, DbManager, DbProperty, SortKey, +}; use std::{path::Path, sync::Arc}; fn manager(dir: &Path) -> DbManager { @@ -8,6 +10,158 @@ fn manager(dir: &Path) -> DbManager { .with_global_sources(dir.join("global")) } +fn duck_lake_source(catalog: &str) -> DataSource { + DataSource { + id: "lake".into(), + name: "DuckLake".into(), + driver: DbDriver::Jdbc, + vendor: "duckdb".into(), + jdbc_driver: "duck".into(), + url: "jdbc:duckdb:".into(), + read_only: true, + duck_lake: Some(DbDuckLake { kind: DbDuckLakeKind::File, value: catalog.into(), data_path: None }), + ..Default::default() + } +} + +fn duck_lake_driver(jar: String) -> DbJdbcDriver { + DbJdbcDriver { + id: "duck".into(), + name: "DuckDB".into(), + vendor: Some("duckdb".into()), + jars: vec![jar], + class_name: "org.duckdb.DuckDBDriver".into(), + url_template: "jdbc:duckdb:".into(), + } +} + +#[tokio::test] +async fn duck_lake_settings_are_validated_and_covered_by_project_approval() -> IdeResult<()> { + let tmp = tempfile::tempdir()?; + let jar = tmp.path().join("fixture.jar"); + std::fs::write(&jar, [])?; + let db = manager(tmp.path()); + let profile = duck_lake_driver(jar.display().to_string()); + let source = duck_lake_source("lake/catalog.ducklake"); + let mut other_profile = profile.clone(); + other_profile.class_name = "test.NotDuckDB".into(); + db.save_jdbc_driver(other_profile)?; + assert!(db.approve_ducklake_source(&source).is_err()); + let directory = tmp.path().join("create"); + assert!(db.create_ducklake("duck", directory.to_str().unwrap()).await.is_err()); + assert!(!directory.exists()); + db.save_jdbc_driver(profile)?; + assert!(db.approve_ducklake_source(&DataSource { duck_lake: None, ..source.clone() }).is_err()); + + let mut invalid_secret = source.clone(); + invalid_secret.duck_lake = + Some(DbDuckLake { kind: DbDuckLakeKind::Secret, value: "key=value".into(), data_path: None }); + let mut data_path = source.clone(); + data_path.duck_lake.as_mut().unwrap().data_path = Some("s3://example/ducklake".into()); + let mut scripted = source.clone(); + scripted.options.startup_script = "CREATE TABLE t (n int)".into(); + for invalid in [ + invalid_secret, + data_path, + scripted, + DataSource { driver: DbDriver::Sqlite, ..source.clone() }, + DataSource { url: "jdbc:duckdb:unrelated.duckdb".into(), ..source.clone() }, + DataSource { read_only: false, ..source.clone() }, + DataSource { save_password: true, ..source.clone() }, + DataSource { + properties: vec![DbProperty { name: "access_mode".into(), value: "READ_WRITE".into() }], + ..source.clone() + }, + ] { + assert!(invalid.resolved().is_err()); + assert!(db.save_sources(vec![invalid.clone()]).await.is_err()); + assert!(db.approve_ducklake_source(&invalid).is_err()); + } + assert!(db.sources()?.is_empty()); + + db.approve_ducklake_source(&DataSource { global: true, ..source.clone() })?; + db.save_sources(vec![source.clone()]).await?; + assert_eq!(db.source("lake")?, source); + let err = db.pool("lake").await.err().expect("global validation must not approve a project connection"); + assert!(err.message.contains("Review this project")); + assert!(db.set_password("lake", Some("unused".into()), true).await.is_err()); + assert!(db.test(&source, Some("unused".into()), None).await.is_err()); + db.approve_ducklake_source(&source)?; + let mut changed = source; + changed.duck_lake.as_mut().unwrap().value = "another/catalog.ducklake".into(); + db.save_sources(vec![changed]).await?; + let err = db.pool("lake").await.err().expect("new catalog path must be approved"); + assert!(err.message.contains("Review this project")); + assert!(serde_json::from_value::(serde_json::json!({"kind":"create", "value":"lake"})).is_err()); + Ok(()) +} + +#[tokio::test] +#[ignore = "requires DUCKDB_JDBC_JAR, DuckLake extension access, and Java 17+"] +async fn duck_lake_creates_only_explicitly_and_reopens_read_only() -> IdeResult<()> { + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR"); + db.save_jdbc_driver(duck_lake_driver(jar))?; + let source = duck_lake_source("lake's files/catalog.ducklake"); + let directory = tmp.path().join("project").join("lake's files"); + let path = directory.to_str().unwrap(); + db.save_sources(vec![source.clone()]).await?; + let err = db.test(&source, None, None).await.expect_err("Test must not create a missing catalog"); + assert!(err.message.contains("does not exist"), "{}", err.message); + assert!(!directory.exists()); + db.approve_ducklake_source(&source)?; + assert!(db.pool("lake").await.is_err()); + assert!(!directory.exists()); + + db.create_ducklake("duck", path).await?; + assert!(directory.join("catalog.ducklake").is_file()); + let err = db.create_ducklake("duck", path).await.expect_err("Create must reject an existing directory"); + assert!(err.message.contains("already exists"), "{}", err.message); + assert!(db.test(&source, None, None).await?.contains("DuckDB")); + + let db = manager(tmp.path()); + assert_eq!(db.source("lake")?, source); + let cancel = CancellationToken::new(); + let console = ConsoleId::new("window", "/lake.sql"); + for scope in [None, Some(console)] { + let result = db + .execute_in_console( + "lake", + "SELECT readonly FROM duckdb_databases() WHERE database_name = current_database() AND type = 'ducklake'", + 0, + 1, + &cancel, + None, + scope, + ) + .await?; + assert_eq!(result.rows, [vec![Some("true".into())]]); + assert!( + db.execute_in_console("lake", "CREATE TABLE main.rejected(id INTEGER)", 0, 1, &cancel, None, scope) + .await + .is_err(), + "the attached catalog must be read-only" + ); + } + assert!(db.schemas("lake").await?.contains(&"main".into())); + assert!(db.tables("lake", "main").await?.is_empty()); + let databases = db.databases("lake").await?; + assert_eq!(databases.current, "openidea_lake"); + assert!(databases.names.contains(&databases.current)); + let catalog = db.database_catalog("lake", &databases.current).await?; + assert!(catalog.iter().any(|schema| schema.name == "main" && schema.tables.is_empty())); + db.release_target_console(console, Some("lake")).await?; + db.disconnect("lake").await; + + let global = DataSource { id: "global-lake".into(), global: true, ..source }; + db.approve_ducklake_source(&global)?; + db.save_sources(vec![global]).await?; + assert!(db.schemas("global-lake").await?.contains(&"main".into())); + db.disconnect("global-lake").await; + Ok(()) +} + #[tokio::test] async fn jdbc_profiles_persist_and_project_files_cannot_start_drivers() -> IdeResult<()> { let tmp = tempfile::tempdir()?; diff --git a/crates/ide-host/src/ops/db.rs b/crates/ide-host/src/ops/db.rs index 88c9bf801a..48e437aeb3 100644 --- a/crates/ide-host/src/ops/db.rs +++ b/crates/ide-host/src/ops/db.rs @@ -33,6 +33,11 @@ pub enum ExecutionEvent { Done { error: Option }, } +#[command(trust = trusted)] +pub fn db_approve_ducklake_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> { + host.project(window)?.db.approve_ducklake_source(&source) +} + #[command(trust = trusted)] pub fn db_approve_jdbc_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> { host.project(window)?.db.approve_jdbc_source(&source) @@ -75,6 +80,12 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec sources_changed(host, window) } +#[command(trust = trusted)] +pub async fn db_create_ducklake(host: &Host, window: &str, jdbc_driver: String, directory: String) -> IdeResult<()> { + let db = host.project(window)?.db.clone(); + db.create_ducklake(&jdbc_driver, &directory).await +} + #[command(trust = trusted)] pub fn db_source_folders(host: &Host, window: &str) -> IdeResult> { // The project's user-created folders and their data source members. @@ -836,6 +847,7 @@ ide_command::domain!( db_consoles_dir, db_consoles, db_create_database, + db_create_ducklake, db_database_catalog, db_catalog_table_details, db_catalog_table_page, @@ -851,6 +863,7 @@ ide_command::domain!( db_history, db_jdbc_driver_classes, db_jdbc_drivers, + db_approve_ducklake_source, db_approve_jdbc_source, db_save_jdbc_driver, db_remove_jdbc_driver, diff --git a/docs/en/guide/database.mdx b/docs/en/guide/database.mdx index aa7afcafbf..b5e70c1054 100644 --- a/docs/en/guide/database.mdx +++ b/docs/en/guide/database.mdx @@ -30,6 +30,14 @@ Choose **New › Data Source › DuckDB**. In **Manage Drivers…**, add the [of Choose **File** to open an existing database or create a new file, **In memory** for a temporary database that lasts until disconnect, or **JDBC URL** to enter a DuckDB URL directly. To inspect an existing file without changing it, enable **Read-only** in **Options**. The official driver applies this setting when it opens the file. +### DuckLake + +Choose **DuckLake** in the DuckDB connection dialog. Select **Catalog file** to browse to an existing catalog, or **DuckDB secret** to enter the name of a DuckDB secret of type `ducklake` configured on the database host. The secret must be available to new JDBC sessions on that host, including after reconnect. On first use, DuckDB installs and loads its official DuckLake extension. See the [DuckLake connection guide](https://ducklake.select/docs/stable/duckdb/usage/connecting) for catalog and storage options. + +OpenIDEA attaches the selected catalog read-only and leaves its metadata version unchanged. To enforce read-only access across the SQL console, give the database account and storage credentials read permissions only. Leave **Data directory** empty to use the storage location recorded in the catalog. If you moved the Parquet files, you can point to their existing directory on the database host. + +To initialize an empty local lake, choose **Create New DuckLake…** and confirm a new directory name. OpenIDEA creates `catalog.ducklake` there and selects it in the dialog. Use **Test Connection** to check access and **OK** to save the source. + ## JDBC drivers For presets with a built-in driver, **Driver** defaults to **Built-in** in the **General** tab. Use **Manage Drivers…** to view or add JDBC profiles for that data source type. Select the profile from **Driver** to use JDBC while keeping the source type and icon. **Go to Driver** opens the selected profile and its JAR list. Choose **New › Data Source › Custom JDBC** for databases without a preset, or open its **Manage Drivers…** to see all profiles and change their associated types. diff --git a/docs/zh/guide/database.mdx b/docs/zh/guide/database.mdx index fb18582eb2..8beb747c90 100644 --- a/docs/zh/guide/database.mdx +++ b/docs/zh/guide/database.mdx @@ -30,6 +30,14 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行 选择 **文件** 可打开已有数据库或创建新文件,选择 **内存** 可创建断开连接后即释放的临时数据库,选择 **JDBC URL** 可直接输入 DuckDB URL。要以只读方式检查已有文件,请在 **选项** 中启用 **只读**。官方驱动会在打开文件时应用此设置。 +### DuckLake + +在 DuckDB 连接对话框中选择 **DuckLake**。选择 **目录文件** 可浏览已有的目录文件,也可以选择 **DuckDB 密钥**,输入数据库主机上已配置的 `ducklake` 类型密钥名称。该密钥必须可供数据库主机上的新 JDBC 会话使用,包括断线重连后的会话。首次使用时,DuckDB 会安装并加载官方 DuckLake 扩展。有关目录和存储选项,请参阅 [DuckLake 连接指南](https://ducklake.select/docs/stable/duckdb/usage/connecting)。 + +OpenIDEA 以只读方式挂载所选目录,并保留现有的元数据版本。要在整个 SQL 控制台中限制写入,请只为数据库账户和存储凭据授予读取权限。将 **数据目录** 留空即可使用目录中记录的存储位置。如果移动了 Parquet 文件,请指定数据库主机上已有的数据目录。 + +要创建本地空湖,请选择 **新建 DuckLake…**,指定并确认一个尚不存在的目录。OpenIDEA 会在其中创建 `catalog.ducklake` 并在对话框中选中该文件。点击 **测试连接** 检查访问权限,再点击 **确定** 保存数据源。 + ## JDBC 驱动 对于提供内置驱动的预设,**常规** 选项卡中的 **驱动** 默认为 **内置**。通过 **管理驱动…** 查看或添加该数据源类型的 JDBC 驱动配置。在 **驱动** 中选中配置后,数据源会使用 JDBC,同时保留原有类型及图标。选择 **转到驱动** 可查看所选配置及其 JAR 文件。对于没有预设的数据库,请选择 **新建 › 数据源 › 自定义 JDBC**。也可以在其中选择 **管理驱动…** 查看所有配置并修改关联类型。 diff --git a/e2e/ducklake-source.spec.ts b/e2e/ducklake-source.spec.ts new file mode 100644 index 0000000000..59854a776f --- /dev/null +++ b/e2e/ducklake-source.spec.ts @@ -0,0 +1,114 @@ +import type { DataSource_Deserialize } from "../src/bindings"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +test("opens an existing DuckLake and creates a new one only after confirmation through mocked desktop IPC", async ({ + workbench: page, +}, info) => { + const driverId = "duckdb-fixture"; + const catalogFile = "/demo/sales/catalog.ducklake"; + const dataPath = "/demo/sales/parquet"; + const newDirectory = "/demo/new-lake"; + await stubDesktop(page); + await page.evaluate( + async ({ driverId, newDirectory }) => { + let sources: DataSource_Deserialize[] = []; + Object.assign(window.__ipc.handlers, { + db_sources: () => sources, + db_connected: () => [], + db_jdbc_drivers: () => [ + { + id: driverId, + vendor: "duckdb", + name: "DuckDB JDBC", + className: "org.duckdb.DuckDBDriver", + jars: ["/mock/duckdb_jdbc.jar"], + urlTemplate: "jdbc:duckdb:{file}", + }, + ], + file_dialog_needs_gtk: () => false, + "plugin:dialog|save": () => newDirectory, + db_test: () => "DuckDB 2.0.1 (mock)", + db_approve_ducklake_source: () => null, + db_set_password: () => null, + db_save_sources: ({ sources: next }: { sources: DataSource_Deserialize[] }) => { + sources = next; + return null; + }, + db_create_ducklake: () => null, + }); + const path = "/src/features/database/store.ts"; + (await import(/* @vite-ignore */ path)).openSourceDialog(null); + }, + { driverId, newDirectory }, + ); + + const draft = page.getByRole("dialog", { name: "New Data Source", exact: true }); + await draft.getByRole("button", { name: "Data source type", exact: true }).click(); + await page.getByRole("option", { name: "DuckDB", exact: true }).click(); + await expect(draft.getByRole("button", { name: "Connection driver" })).toHaveText("DuckDB JDBC"); + await draft.getByLabel("Name:", { exact: true }).fill("Sales Lake"); + await draft.getByRole("button", { name: "DuckLake", exact: true }).click(); + await draft.getByLabel("Catalog file:", { exact: true }).fill(catalogFile); + await draft.getByLabel("Data directory:", { exact: true }).fill(dataPath); + await expect(draft.locator("#db-url")).toHaveCount(0); + await draft.getByRole("tab", { name: "Options", exact: true }).click(); + const readOnly = draft.getByRole("checkbox", { name: "Read-only", exact: true }); + await expect(readOnly).toBeChecked(); + await expect(readOnly).toBeDisabled(); + await draft.getByRole("tab", { name: "General", exact: true }).click(); + + await draft.getByRole("button", { name: "Test Connection", exact: true }).click(); + await expect(draft.getByRole("status")).toHaveText("Succeeded: DuckDB 2.0.1 (mock)"); + const connection = { + name: "Sales Lake", + driver: "jdbc", + vendor: "duckdb", + jdbcDriver: driverId, + url: "jdbc:duckdb:", + readOnly: true, + savePassword: false, + properties: [], + duckLake: { kind: "file", value: catalogFile, dataPath }, + }; + expect(await ipcCalls(page, "db_test")).toEqual([ + expect.objectContaining({ password: null, sshSecret: null, source: expect.objectContaining(connection) }), + ]); + expect(await ipcCalls(page, "db_create_ducklake")).toHaveLength(0); + await draft.screenshot({ path: info.outputPath("ducklake-existing.png"), animations: "disabled" }); + await draft.getByRole("button", { name: "OK", exact: true }).click(); + await expect(draft).not.toBeVisible(); + expect(await ipcCalls(page, "db_approve_ducklake_source")).toEqual([{ source: expect.objectContaining(connection) }]); + expect(await ipcCalls(page, "db_approve_jdbc_source")).toHaveLength(0); + expect(await ipcCalls(page, "db_save_sources")).toEqual([{ sources: [expect.objectContaining(connection)] }]); + + await page.evaluate(async () => { + const path = "/src/features/database/store.ts"; + const { openSourceDialog, useDatabase } = await import(/* @vite-ignore */ path); + openSourceDialog(useDatabase.getState().sources[0]); + }); + const reopened = page.getByRole("dialog", { name: "Data Source: Sales Lake", exact: true }); + const file = reopened.getByLabel("Catalog file:", { exact: true }); + await expect(file).toHaveValue(catalogFile); + await expect(reopened.getByLabel("Data directory:", { exact: true })).toHaveValue(dataPath); + const create = reopened.getByRole("button", { name: "Create New DuckLake…", exact: true }); + const confirmation = page.getByRole("dialog", { name: "Create New DuckLake", exact: true }); + await create.click(); + await expect(confirmation).toContainText(newDirectory); + await expect(confirmation).toContainText("The directory must not already exist."); + expect(await ipcCalls(page, "db_create_ducklake")).toHaveLength(0); + await confirmation.screenshot({ path: info.outputPath("ducklake-create-confirmation.png"), animations: "disabled" }); + await confirmation.getByRole("button", { name: "Cancel", exact: true }).click(); + await expect(confirmation).not.toBeVisible(); + await expect(file).toHaveValue(catalogFile); + expect(await ipcCalls(page, "db_create_ducklake")).toHaveLength(0); + + await create.click(); + await confirmation.getByRole("button", { name: "Create", exact: true }).click(); + await expect(reopened.getByRole("status")).toHaveText("DuckLake created. The data source opens it read-only."); + await expect(file).toHaveValue(newDirectory + "/catalog.ducklake"); + await expect(reopened.getByLabel("Data directory:", { exact: true })).toHaveValue(""); + expect(await ipcCalls(page, "db_create_ducklake")).toEqual([{ jdbcDriver: driverId, directory: newDirectory }]); + expect(await ipcCalls(page, "db_save_sources")).toHaveLength(1); + expect(await ipcCalls(page, "db_test")).toHaveLength(1); + await reopened.screenshot({ path: info.outputPath("ducklake-created.png"), animations: "disabled" }); +}); diff --git a/java/jdbc-bridge/openidea-jdbc-bridge.jar b/java/jdbc-bridge/openidea-jdbc-bridge.jar index cceb90cb88..961451b029 100644 Binary files a/java/jdbc-bridge/openidea-jdbc-bridge.jar and b/java/jdbc-bridge/openidea-jdbc-bridge.jar differ diff --git a/java/jdbc-bridge/src/ai/openidea/jdbc/MultiplexBridge.java b/java/jdbc-bridge/src/ai/openidea/jdbc/MultiplexBridge.java index 3195a503c3..31e13ae03a 100644 --- a/java/jdbc-bridge/src/ai/openidea/jdbc/MultiplexBridge.java +++ b/java/jdbc-bridge/src/ai/openidea/jdbc/MultiplexBridge.java @@ -26,10 +26,12 @@ final class MultiplexBridge { private final ConcurrentMap sessions = new ConcurrentHashMap<>(); // Closing drivers still count towards the cap until their Connection.close returns. private final Set live = ConcurrentHashMap.newKeySet(); + private record Settings(List parameters, boolean duckLake) {} + // Reserve before large writes and encodings, not while JDBC executes. This keeps // frame copies and encoding temporaries within the 192 MiB JVM's headroom. private final Semaphore largeReplies = new Semaphore(1, true); - private volatile List settings; + private volatile Settings settings; private final AtomicBoolean stopping = new AtomicBoolean(); MultiplexBridge(DataInputStream input, DataOutputStream output) { @@ -97,8 +99,9 @@ final class MultiplexBridge { session.canceller.shutdown(); } - private Connection connect(List options) throws Exception { - if (!options.get(0).equals("org.duckdb.DuckDBDriver")) return OpenIdeaJdbc.connect(options); + private Connection connect(Settings options) throws Exception { + if (!options.parameters().get(0).equals(OpenIdeaJdbc.DUCKDB_CLASS)) + return OpenIdeaJdbc.connect(options.parameters()); // A second DuckDB login would create a different unnamed in-memory database. // Call duplicate on the service worker so it never races another operation // on the same JDBC Connection. @@ -106,7 +109,18 @@ final class MultiplexBridge { if (service == null) throw new SQLException("The DuckDB service connection is unavailable"); return service.worker.submit(() -> { Connection source = service.jdbc.connection; - return (Connection) source.getClass().getMethod("duplicate").invoke(source); + Connection duplicate = (Connection) source.getClass().getMethod("duplicate").invoke(source); + // Attachments are shared by DuckDB, but the current catalog is connection-local. + if (options.duckLake()) { + try (var statement = duplicate.createStatement()) { + statement.execute("USE " + OpenIdeaJdbc.DUCKLAKE_CATALOG); + } catch (SQLException failure) { + try { duplicate.close(); } + catch (SQLException closeFailure) { failure.addSuppressed(closeFailure); } + throw failure; + } + } + return duplicate; }).get(); } @@ -124,12 +138,13 @@ final class MultiplexBridge { return; } - boolean open = op.equals("open"); - List options = settings; + boolean duckLake = op.equals("openDuckLake"); + boolean open = op.equals("open") || duckLake; + Settings options = settings; if (open) { boolean valid = connection == SERVICE - ? fields.size() >= 6 && fields.size() % 2 == 0 - : fields.size() == 1 && options != null; + ? (duckLake ? fields.size() == 9 : fields.size() >= 6 && fields.size() % 2 == 0) + : !duckLake && fields.size() == 1 && options != null; if (!valid || session != null) { send(id, status("Invalid JDBC connection open request")); return; @@ -138,7 +153,7 @@ final class MultiplexBridge { send(id, status("JDBC connection limit reached. Close a console or wait for its connection to finish closing, then try again.")); return; } - if (connection == SERVICE) options = List.copyOf(fields.subList(1, fields.size())); + if (connection == SERVICE) options = new Settings(List.copyOf(fields.subList(1, fields.size())), duckLake); session = new Session(connection); sessions.put(connection, session); live.add(session); @@ -161,7 +176,7 @@ final class MultiplexBridge { } private void schedule(Session session, OpenIdeaJdbc.Work work, List fields, - boolean open, List options) { + boolean open, Settings options) { session.worker.execute(() -> { try (var buffer = new ReplyBuffer(largeReplies)) { var answer = session.jdbc.reply(work, fields, diff --git a/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java b/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java index b9da003b24..0ce3fb3e24 100644 --- a/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java +++ b/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java @@ -4,6 +4,12 @@ package ai.openidea.jdbc; import java.io.*; import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; import java.sql.*; import java.util.*; import java.util.concurrent.*; @@ -11,6 +17,9 @@ import java.util.concurrent.atomic.AtomicReference; public final class OpenIdeaJdbc { static final int LIMIT = 16 * 1024 * 1024; + static final String DUCKDB_CLASS = "org.duckdb.DuckDBDriver"; + private static final String DUCKDB_MEMORY = "jdbc:duckdb:"; + static final String DUCKLAKE_CATALOG = "openidea_lake"; Connection connection; boolean catalogs; boolean namespaceKnown; @@ -68,7 +77,7 @@ public final class OpenIdeaJdbc { if (!a.get(2).isEmpty()) props.setProperty("user", a.get(2)); if (!a.get(3).isEmpty()) props.setProperty("password", a.get(3)); boolean readOnly = Boolean.parseBoolean(a.get(4)); - boolean duckDbReadOnly = readOnly && className.equals("org.duckdb.DuckDBDriver") && url.startsWith("jdbc:duckdb:"); + boolean duckDbReadOnly = readOnly && className.equals(DUCKDB_CLASS) && url.startsWith(DUCKDB_MEMORY); if (duckDbReadOnly) { // DuckDB fixes its access mode at open, and options in the URL take precedence. for (String key : props.stringPropertyNames()) checkDuckDbReadOnly(key, props.getProperty(key)); @@ -104,9 +113,7 @@ public final class OpenIdeaJdbc { private void open(List args, DataOutputStream out, OpenConnection opener) throws Exception { Connection opened = opener.open(args); try { - var m = opened.getMetaData(); - header(out, "version", "quote"); - row(out, m.getDatabaseProductName() + " " + m.getDatabaseProductVersion(), m.getIdentifierQuoteString()); + openMetadata(opened, out); connection = opened; } catch (Exception | LinkageError failure) { try { opened.close(); } catch (SQLException ignored) {} @@ -118,6 +125,138 @@ public final class OpenIdeaJdbc { if (connection != null) connection.close(); } + private static void openMetadata(Connection connection, DataOutputStream out) throws SQLException, IOException { + var m = connection.getMetaData(); + header(out, "version", "quote"); + row(out, m.getDatabaseProductName() + " " + m.getDatabaseProductVersion(), m.getIdentifierQuoteString()); + } + + private static class DuckLakeUnavailable extends SQLException { + DuckLakeUnavailable(String message) { super(message); } + } + + private static Path absoluteLakePath(String value) throws DuckLakeUnavailable { + try { + Path path = Path.of(value); + if (path.isAbsolute()) return path; + } catch (InvalidPathException ignored) {} + throw new DuckLakeUnavailable("DuckLake requires an absolute local path on the database host."); + } + + private static BasicFileAttributes lakePathAttributes(Path path, String description) throws DuckLakeUnavailable { + try { + return Files.readAttributes(path, BasicFileAttributes.class); + } catch (NoSuchFileException ignored) { + throw new DuckLakeUnavailable("The DuckLake " + description + " does not exist on the database host."); + } catch (IOException | SecurityException ignored) { + throw new DuckLakeUnavailable("The DuckLake " + description + " could not be accessed on the database host. Check permissions."); + } + } + + private static String sqlLiteral(String value) { + return "'" + value.replace("'", "''") + "'"; + } + + void openDuckLake(Work work, List a, DataOutputStream out) throws Exception { + if (a.size() != 8 || !a.get(0).equals(DUCKDB_CLASS) || !a.get(1).equals(DUCKDB_MEMORY) + || !a.get(2).isEmpty() || !a.get(3).isEmpty()) + throw new DuckLakeUnavailable("DuckLake requires a standard DuckDB connection without JDBC overrides."); + if (connection != null) + throw new DuckLakeUnavailable("DuckLake requires a new JDBC session."); + + String mode = a.get(5), value = a.get(6), dataPath = a.get(7); + boolean create = mode.equals("create"), secret = mode.equals("secret"); + boolean readOnly = !create; + if (!create && !secret && !mode.equals("file")) + throw new DuckLakeUnavailable("Choose to open a DuckLake file or secret, or create a new DuckLake."); + if (!a.get(4).equals(Boolean.toString(readOnly))) + throw new DuckLakeUnavailable("Existing DuckLake catalogs must be opened read-only, and creation uses a separate session."); + if (create && !dataPath.isEmpty()) + throw new DuckLakeUnavailable("New DuckLake catalogs use their default data location."); + + Path catalog = null; + if (secret) { + if (!value.matches("[A-Za-z_][A-Za-z0-9_]*")) + throw new DuckLakeUnavailable("Enter an existing DuckLake secret name using letters, digits or underscores."); + } else { + catalog = absoluteLakePath(value); + if (!create && !lakePathAttributes(catalog, "catalog file").isRegularFile()) + throw new DuckLakeUnavailable("Choose a regular DuckLake catalog file on the database host."); + } + if (!dataPath.isEmpty() && !lakePathAttributes(absoluteLakePath(dataPath), "data directory").isDirectory()) + throw new DuckLakeUnavailable("Choose a DuckLake data directory on the database host."); + + Driver driver = Class.forName(DUCKDB_CLASS).asSubclass(Driver.class).getConstructor().newInstance(); + Connection session = driver.connect(DUCKDB_MEMORY, new Properties()); + if (session == null) throw new UnsupportedUrl(); + + boolean directoryCreated = false; + String recovery = " If the directory contains catalog.ducklake, try opening it. Otherwise choose a new directory."; + String failure = "DuckLake could not load the official extension. Check the DuckDB version and extension access."; + try { + try (Statement st = session.createStatement()) { + work.begin(st); + st.execute("INSTALL ducklake FROM core"); + st.execute("LOAD ducklake"); + if (secret) { + failure = "DuckLake could not resolve the named secret on the database host."; + try (var lookup = session.prepareStatement( + "SELECT 1 FROM duckdb_secrets() WHERE name = ? AND type = 'ducklake'")) { + work.begin(lookup); + lookup.setString(1, value); + try (var matches = lookup.executeQuery()) { + if (!matches.next()) + throw new DuckLakeUnavailable("The named DuckLake secret was not found on the database host."); + } + } + work.begin(st); + } + if (create) { + failure = "DuckLake could not create the new directory. Check its parent and permissions."; + try { + Files.createDirectory(catalog); + } catch (FileAlreadyExistsException ignored) { + throw new DuckLakeUnavailable("The DuckLake directory already exists." + recovery); + } + directoryCreated = true; + catalog = catalog.resolve("catalog.ducklake"); + work.begin(st); + } + + failure = create ? "DuckLake could not initialize the new catalog. Check the new directory." + : "DuckLake could not open the catalog read-only. Check its metadata and data access."; + String location = secret ? value : catalog.toString(); + String options = create ? "CREATE_IF_NOT_EXISTS true" : "READ_ONLY, CREATE_IF_NOT_EXISTS false"; + if (!dataPath.isEmpty()) options += ", DATA_PATH " + sqlLiteral(dataPath) + ", OVERRIDE_DATA_PATH true"; + st.execute("ATTACH " + sqlLiteral("ducklake:" + location) + " AS " + DUCKLAKE_CATALOG + + " (" + options + ", AUTOMATIC_MIGRATION false)"); + st.execute("USE " + DUCKLAKE_CATALOG); + try (var db = st.executeQuery("SELECT readonly FROM duckdb_databases() WHERE database_name = '" + + DUCKLAKE_CATALOG + "' AND database_name = current_database() AND type = 'ducklake'")) { + if (!db.next() || db.getBoolean(1) != readOnly) throw new DuckLakeUnavailable(failure); + } + work.begin(st); + } + openMetadata(session, out); + // Only a read-only session is published for later requests. + if (create) { + failure = "DuckLake could not finish creating the catalog. Check the new directory."; + session.close(); + } else { + connection = session; + } + } catch (Exception | LinkageError e) { + String message = work.isCancelled() ? (create ? "DuckLake creation cancelled." : "DuckLake connection cancelled.") + : e instanceof DuckLakeUnavailable ? e.getMessage() : failure; + if (directoryCreated) message += " The new directory was kept." + recovery; + throw new DuckLakeUnavailable(message); + } finally { + if (connection != session) { + try { session.close(); } catch (SQLException ignored) {} + } + } + } + static String pattern(DatabaseMetaData m, String literal) throws SQLException { String escape = m.getSearchStringEscape(); if (escape == null || escape.isEmpty()) return literal; @@ -290,6 +429,8 @@ public final class OpenIdeaJdbc { statement = st; } + synchronized boolean isCancelled() { return cancelled; } + void cancel() { Statement st; synchronized (this) { @@ -340,6 +481,7 @@ public final class OpenIdeaJdbc { reply.writeBoolean(true); switch (op) { case "open" -> open(a, reply, opener); + case "openDuckLake" -> openDuckLake(work, a, reply); case "catalogs" -> catalogs(reply); case "schemas" -> schemas(a.isEmpty() ? null : a.get(0), reply); case "tables", "columns", "schemaColumns" -> metadata(op, a, reply); @@ -404,11 +546,11 @@ public final class OpenIdeaJdbc { 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) { + } else if (e instanceof ReadOnlyUnavailable || e instanceof DuckLakeUnavailable) { text(reply, e.getMessage()); } else if (e instanceof UnsupportedUrl) { text(reply, "The selected JDBC driver does not accept this URL"); - } else if (op.equals("open")) { + } else if (op.equals("open") || op.equals("openDuckLake")) { // 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() diff --git a/java/jdbc-bridge/tests/SelfTest.java b/java/jdbc-bridge/tests/SelfTest.java index 76ba45f926..4714c5e930 100644 --- a/java/jdbc-bridge/tests/SelfTest.java +++ b/java/jdbc-bridge/tests/SelfTest.java @@ -185,6 +185,17 @@ public class SelfTest { return bytes; } + static void rejectedLake(DataOutputStream out, DataInputStream in, int connection, String expected, String... fields) + throws IOException { + sendOn(out, 40, connection, fields); + try (var response = new DataInputStream(new ByteArrayInputStream(expect(in, 40, 0).data()))) { + assert !response.readBoolean(); + String message = new String(response.readNBytes(response.readInt()), StandardCharsets.UTF_8); + assert message.contains(expected) : message; + assert !message.contains("private-token") : message; + } + } + static void sendOn(DataOutputStream out, long id, int connection, String... fields) throws IOException { out.writeLong(id); out.writeInt(connection); @@ -227,6 +238,33 @@ public class SelfTest { try (var out = new DataOutputStream(child.getOutputStream()); var in = new DataInputStream(child.getInputStream()); var log = child.errorReader()) { + String duckdb = "org.duckdb.DuckDBDriver", memory = "jdbc:duckdb:"; + rejectedLake(out, in, 0, "standard DuckDB connection", "openDuckLake", Fixture.class.getName(), memory, + "", "", "true", "secret", "sample", ""); + rejectedLake(out, in, 0, "standard DuckDB connection", "openDuckLake", duckdb, memory + ";private-token", + "", "", "true", "secret", "sample", ""); + rejectedLake(out, in, 0, "standard DuckDB connection", "openDuckLake", duckdb, memory, + "", "private-token", "true", "secret", "sample", ""); + rejectedLake(out, in, 0, "Invalid JDBC connection open request", "openDuckLake", duckdb, memory, + "", "", "true", "secret", "sample", "", "arbitrary"); + rejectedLake(out, in, 1, "Invalid JDBC connection open request", "openDuckLake", duckdb, memory, + "", "", "true", "secret", "sample", ""); + rejectedLake(out, in, 0, "read-only", "openDuckLake", duckdb, memory, + "", "", "false", "file", "unused", ""); + rejectedLake(out, in, 0, "absolute", "openDuckLake", duckdb, memory, + "", "", "true", "file", "relative/catalog.ducklake", ""); + Path temp = Path.of(System.getProperty("java.io.tmpdir")).toAbsolutePath(); + rejectedLake(out, in, 0, "regular DuckLake catalog file", "openDuckLake", duckdb, memory, + "", "", "true", "file", temp.toString(), ""); + rejectedLake(out, in, 0, "does not exist", "openDuckLake", duckdb, memory, + "", "", "true", "file", temp.resolve(UUID.randomUUID() + "-private-token").toString(), ""); + rejectedLake(out, in, 0, "existing DuckLake secret name", "openDuckLake", duckdb, memory, + "", "", "true", "secret", "postgresql://user:private-token@localhost/catalog", ""); + rejectedLake(out, in, 0, "absolute", "openDuckLake", duckdb, memory, + "", "", "true", "secret", "sample", "s3://bucket/path"); + rejectedLake(out, in, 0, "default data location", "openDuckLake", duckdb, memory, + "", "", "false", "create", "unused", "nonempty"); + sendOn(out, 100, 0, "open", Fixture.class.getName(), "jdbc:fixture:", "", "", "false"); try { expect(in, 100, 1); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 2c387a74d0..3f7e2633e8 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -115,6 +115,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_ducklake_source trusted project_host bindings sync db_approve_external_tunnel trusted desktop bindings async db_approve_jdbc_source trusted project_host bindings sync db_catalog_table_details trusted project_host bindings async @@ -126,6 +127,7 @@ db_console_path always project_host bin db_consoles always project_host bindings sync db_consoles_dir always project_host bindings sync db_create_database trusted project_host bindings async +db_create_ducklake trusted project_host bindings async db_database_catalog trusted project_host bindings async db_databases trusted project_host bindings async db_ddl trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index afbd988bb8..11a0e51526 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -374,6 +374,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 })), + dbApproveDucklakeSource: (source: DataSource_Deserialize) => typedError(__TAURI_INVOKE("db_approve_ducklake_source", { source })), /** Records the exact helper and destination reviewed in the local data-source dialog. */ dbApproveExternalTunnel: (source: DataSource_Deserialize) => typedError(__TAURI_INVOKE("db_approve_external_tunnel", { source })), dbApproveJdbcSource: (source: DataSource_Deserialize) => typedError(__TAURI_INVOKE("db_approve_jdbc_source", { source })), @@ -388,6 +389,7 @@ export const commands = { /** The project view root for every data source's query consoles (`/consoles/db`). */ dbConsolesDir: () => typedError(__TAURI_INVOKE("db_consoles_dir")), dbCreateDatabase: (id: string, template: string, statement: string) => typedError(__TAURI_INVOKE("db_create_database", { id, template, statement })), + dbCreateDucklake: (jdbcDriver: string, directory: string) => typedError(__TAURI_INVOKE("db_create_ducklake", { jdbcDriver, directory })), dbDatabaseCatalog: (id: string, database: string) => typedError(__TAURI_INVOKE("db_database_catalog", { id, database })), dbDatabases: (id: string) => typedError(__TAURI_INVOKE("db_databases", { id })), dbDdl: (id: string, schema: string, table: string) => typedError(__TAURI_INVOKE("db_ddl", { id, schema, table })), @@ -5628,6 +5630,7 @@ export type DataSource_Deserialize = { properties?: DbProperty[], /** Snowflake settings (`None`: not a Snowflake data source, or all defaults). */ snowflake?: DbSnowflake | null, + duckLake?: DbDuckLake_Deserialize | null, /** * Stored app-wide and listed in every project. Implied by the file it is read from, * so not written to it. @@ -5675,6 +5678,7 @@ export type DataSource_Serialize = { properties: DbProperty[], /** Snowflake settings (`None`: not a Snowflake data source, or all defaults). */ snowflake: DbSnowflake | null, + duckLake?: DbDuckLake_Serialize | null, /** * Stored app-wide and listed in every project. Implied by the file it is read from, * so not written to it. @@ -5788,6 +5792,29 @@ export type DbDriver = "sqlite" | "postgres" | /** Oracle Database (pure-Rust thin driver, no client library). */ "oracle" | "snowflake" | "jdbc"; +/** How to open an existing DuckLake catalog read-only through DuckDB. */ +export type DbDuckLake = DbDuckLake_Serialize | DbDuckLake_Deserialize; + +export type DbDuckLakeKind = "file" | "secret"; + +/** How to open an existing DuckLake catalog read-only through DuckDB. */ +export type DbDuckLake_Deserialize = { + kind: DbDuckLakeKind, + /** A local catalog file or an existing DuckDB secret name. */ + value: string, + /** An existing local data directory overriding the catalog's data path. */ + dataPath?: string | null, +}; + +/** How to open an existing DuckLake catalog read-only through DuckDB. */ +export type DbDuckLake_Serialize = { + kind: DbDuckLakeKind, + /** A local catalog file or an existing DuckDB secret name. */ + value: string, + /** An existing local data directory overriding the catalog's data path. */ + dataPath?: string | null, +}; + export type DbDumpContent = "all" | "schemaOnly" | "dataOnly"; export type DbDumpFormat = diff --git a/src/features/database/JdbcSourceDialog.test.tsx b/src/features/database/JdbcSourceDialog.test.tsx index bffa14007d..f4298cd3d7 100644 --- a/src/features/database/JdbcSourceDialog.test.tsx +++ b/src/features/database/JdbcSourceDialog.test.tsx @@ -1,6 +1,6 @@ import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { DataSource, DbJdbcDriver, ProjectInfo } from "@/platform/ipc"; +import { IpcError, type DataSource, type DbJdbcDriver, type ProjectInfo } from "@/platform/ipc"; import { registerHostPathChooser } from "@/platform/choosePath"; import { useProject } from "@/platform/project"; import { useRemote } from "@/platform/remote"; @@ -11,7 +11,13 @@ import { sourceIcon, sourceLabel } from "./model"; import { newMenu, nodeMenu } from "./treeMenu"; import { useDatabase } from "./store"; -const backend = vi.hoisted(() => ({ call: vi.fn(), saveSource: vi.fn(), pick: vi.fn(), pickNew: vi.fn() })); +const backend = vi.hoisted(() => ({ + call: vi.fn(), + saveSource: vi.fn(), + pick: vi.fn(), + pickNew: vi.fn(), + confirm: vi.fn(), +})); vi.mock("@/platform/ipc", async (importOriginal) => { const real = await importOriginal(); const request = @@ -27,9 +33,11 @@ vi.mock("@/platform/ipc", async (importOriginal) => { clipboardText: request("clipboard"), dbJdbcDriverClasses: request("classes"), dbApproveJdbcSource: request("approve"), + dbApproveDucklakeSource: request("approveLake"), dbSaveJdbcDriver: request("save"), dbRemoveJdbcDriver: request("remove"), dbTest: request("test"), + dbCreateDucklake: request("createLake"), }, }; }); @@ -38,6 +46,10 @@ vi.mock("./store", async (importOriginal) => ({ saveSource: backend.saveSource, })); vi.mock("@/platform/dialog", () => ({ open: backend.pick, save: backend.pickNew })); +vi.mock("@/workbench/messages", async (importOriginal) => ({ + ...(await importOriginal()), + confirm: backend.confirm, +})); const driver: DbJdbcDriver = { id: "example-driver", @@ -60,6 +72,7 @@ beforeEach(() => { backend.saveSource.mockResolvedValue(undefined); backend.pick.mockResolvedValue(driver.jars); backend.pickNew.mockResolvedValue(null); + backend.confirm.mockResolvedValue(false); useDatabase.setState({ sources: [], dialog: null, loaded: true }); useProject.setState({ project: null }); }); @@ -79,6 +92,201 @@ describe("DuckDB data sources", () => { return dialog; }; + it("tests and saves an existing DuckLake file read-only", async () => { + backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "DuckDB")); + backend.pick.mockResolvedValueOnce("/tmp/warehouse.ducklake"); + startDuckDb(); + fireEvent.click(screen.getByRole("button", { name: "DuckLake" })); + const catalog = screen.getByLabelText("Catalog file:"); + const testConnection = screen.getByRole("button", { name: "Test Connection" }); + fireEvent.change(catalog, { target: { value: "relative.ducklake" } }); + expect(testConnection).toBeDisabled(); + fireEvent.click(screen.getByRole("button", { name: "Browse for DuckLake catalog" })); + await waitFor(() => expect(catalog).toHaveValue("/tmp/warehouse.ducklake")); + expect(backend.pick).toHaveBeenCalledWith(expect.objectContaining({ directory: false, multiple: false })); + expect(screen.queryByLabelText("User:")).toBeNull(); + expect(screen.queryByLabelText("Password:")).toBeNull(); + expect(screen.queryByRole("tab", { name: "Advanced" })).toBeNull(); + + fireEvent.click(screen.getByRole("tab", { name: "Options" })); + expect(screen.getByRole("checkbox", { name: "Read-only" })).toBeChecked(); + expect(screen.getByRole("checkbox", { name: "Read-only" })).toBeDisabled(); + fireEvent.click(testConnection); + const source = expect.objectContaining({ + driver: "jdbc", + vendor: "duckdb", + jdbcDriver: duckdb.id, + url: "jdbc:duckdb:", + readOnly: true, + user: "", + savePassword: false, + properties: [], + duckLake: { kind: "file", value: "/tmp/warehouse.ducklake", dataPath: null }, + }); + await waitFor(() => expect(backend.call).toHaveBeenCalledWith(["test", source, null, null])); + const save = screen.getByRole("button", { name: "OK" }); + await waitFor(() => expect(save).toBeEnabled()); + fireEvent.click(save); + await waitFor(() => expect(backend.saveSource).toHaveBeenCalledWith(source, null, undefined)); + expect(backend.call).toHaveBeenCalledWith(["approveLake", source]); + expect(backend.call.mock.calls.map(([request]) => request[0])).not.toContain("createLake"); + }); + + it.each([ + { + global: false, + kind: "protocol" as const, + message: "command db_approve_ducklake_source is not available remotely", + expected: "Update the remote OpenIDEA server to save DuckLake data sources.", + }, + { + global: true, + kind: "protocol" as const, + message: "command db_approve_ducklake_source is not available remotely", + expected: "Update the remote OpenIDEA server to save DuckLake data sources.", + }, + { + global: false, + kind: "invalidInput" as const, + message: "DuckLake requires a valid catalog file", + expected: "DuckLake requires a valid catalog file", + }, + ])("stops before saving a DuckLake when $kind approval fails (global=$global)", async (entry) => { + backend.call.mockImplementation(async ([op]) => { + if (op === "approveLake") throw new IpcError({ kind: entry.kind, message: entry.message }); + return op === "list" ? [duckdb] : undefined; + }); + render( + , + ); + const save = screen.getByRole("button", { name: "OK" }); + await waitFor(() => expect(save).toBeEnabled()); + fireEvent.click(save); + expect(await screen.findByText(entry.expected)).toBeVisible(); + expect(backend.call.mock.calls.map(([request]) => request[0])).toEqual(["list", "approveLake"]); + expect(backend.saveSource).not.toHaveBeenCalled(); + }); + + it("restores the Lake secret and restricts data directory overrides to host paths", async () => { + backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "DuckDB")); + backend.pick.mockResolvedValueOnce("/tmp/lake-data"); + render( + , + ); + expect(screen.getByRole("button", { name: "DuckLake", pressed: true })).toBeVisible(); + const secret = screen.getByLabelText("Secret name:"); + expect(secret).toHaveValue("warehouse_catalog"); + const testConnection = screen.getByRole("button", { name: "Test Connection" }); + await waitFor(() => expect(testConnection).toBeEnabled()); + fireEvent.change(secret, { target: { value: "postgres:dbname=example" } }); + expect(testConnection).toBeDisabled(); + fireEvent.change(secret, { target: { value: "warehouse_catalog" } }); + const dataDirectory = screen.getByLabelText("Data directory:"); + fireEvent.change(dataDirectory, { target: { value: "s3://example/data" } }); + expect(testConnection).toBeDisabled(); + fireEvent.click(screen.getByRole("button", { name: "Browse for DuckLake data directory" })); + await waitFor(() => expect(dataDirectory).toHaveValue("/tmp/lake-data")); + expect(backend.pick).toHaveBeenCalledWith(expect.objectContaining({ directory: true, multiple: false })); + fireEvent.click(testConnection); + await waitFor(() => + expect(backend.call).toHaveBeenCalledWith([ + "test", + expect.objectContaining({ + readOnly: true, + user: "", + savePassword: false, + properties: [], + options: expect.objectContaining({ startupScript: "", defaultSchema: "", timeZone: "", transaction: "auto" }), + duckLake: { kind: "secret", value: "warehouse_catalog", dataPath: "/tmp/lake-data" }, + }), + null, + null, + ]), + ); + }); + + it("creates a new DuckLake only after a separate confirmation", async () => { + backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : undefined)); + backend.pickNew.mockResolvedValue("/tmp/new-lake"); + startDuckDb(); + fireEvent.click(screen.getByRole("button", { name: "DuckLake" })); + const create = screen.getByRole("button", { name: "Create New DuckLake…" }); + await waitFor(() => expect(create).toBeEnabled()); + expect(screen.getByRole("button", { name: "OK" })).toBeDisabled(); + fireEvent.click(create); + await waitFor(() => expect(backend.confirm).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(create).toBeEnabled()); + expect(backend.confirm).toHaveBeenCalledWith({ + title: "Create New DuckLake", + message: "Create a DuckLake in '/tmp/new-lake'? The directory must not already exist.", + ok: "Create", + }); + expect(backend.call.mock.calls.map(([request]) => request[0])).not.toContain("createLake"); + + backend.confirm.mockResolvedValueOnce(true); + fireEvent.click(create); + await waitFor(() => expect(backend.call).toHaveBeenCalledWith(["createLake", duckdb.id, "/tmp/new-lake"])); + expect(await screen.findByText("DuckLake created. The data source opens it read-only.")).toBeVisible(); + expect(screen.getByLabelText("Catalog file:")).toHaveValue("/tmp/new-lake/catalog.ducklake"); + const ops = backend.call.mock.calls.map(([request]) => request[0]); + expect(ops.filter((op) => op === "createLake")).toHaveLength(1); + expect(ops).not.toContain("test"); + expect(backend.saveSource).not.toHaveBeenCalled(); + }); + + it("browses DuckLake paths on the database host in a remote window", async () => { + const choose = vi + .fn() + .mockResolvedValueOnce(["/srv/project/catalog.ducklake"]) + .mockResolvedValueOnce(["/srv/project/data"]) + .mockResolvedValueOnce(["/srv/project/new-lake"]); + const unregister = registerHostPathChooser(choose); + useRemote.setState({ session: { root: "/srv/project", os: "linux", commands: [] } as never }); + useProject.setState({ project: { root: "/srv/project" } as ProjectInfo }); + try { + backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "OK")); + startDuckDb(); + fireEvent.click(screen.getByRole("button", { name: "DuckLake" })); + fireEvent.click(screen.getByRole("button", { name: "Browse for DuckLake catalog" })); + await waitFor(() => expect(screen.getByLabelText("Catalog file:")).toHaveValue("/srv/project/catalog.ducklake")); + fireEvent.click(screen.getByRole("button", { name: "Browse for DuckLake data directory" })); + await waitFor(() => expect(screen.getByLabelText("Data directory:")).toHaveValue("/srv/project/data")); + fireEvent.click(screen.getByRole("button", { name: "Create New DuckLake…" })); + await waitFor(() => expect(backend.confirm).toHaveBeenCalled()); + expect(choose).toHaveBeenNthCalledWith(1, expect.objectContaining({ directory: false })); + expect(choose).toHaveBeenNthCalledWith(2, expect.objectContaining({ directory: true })); + expect(choose).toHaveBeenNthCalledWith(3, expect.objectContaining({ save: true })); + expect(backend.pick).not.toHaveBeenCalled(); + expect(backend.pickNew).not.toHaveBeenCalled(); + expect(backend.call.mock.calls.map(([request]) => request[0])).not.toContain("createLake"); + } finally { + unregister(); + useRemote.setState({ session: null }); + } + }); + it("offers DuckDB in the new data source menu", () => { const dataSource = newMenu().find((item) => "label" in item && item.label === "Data Source"); expect(dataSource && "submenu" in dataSource && dataSource.submenu).toEqual( diff --git a/src/features/database/SourceDialog.tsx b/src/features/database/SourceDialog.tsx index 81c53a271a..63988c8a09 100644 --- a/src/features/database/SourceDialog.tsx +++ b/src/features/database/SourceDialog.tsx @@ -48,17 +48,25 @@ import { DUCKDB_JDBC_PREFIX, VENDORS, blankSnowflake, sourceUrl, vendorById, ven import { JdbcDriverProfiles, jdbcProfileOption, useJdbcDrivers } from "./JdbcDriverProfiles"; import styles from "./Database.module.css"; import { isImeKey } from "@/platform/ime"; +import { confirm } from "@/workbench/messages"; type Tab = "general" | "options" | "ssh" | "schemas" | "advanced"; type ConnectionMethod = "direct" | "ssh" | "external"; -type DuckDbMode = "file" | "memory" | "url"; +type DuckDbMode = "file" | "memory" | "url" | "ducklake"; +type DuckLake = NonNullable; const DUCKDB_MODES: Array<{ id: DuckDbMode; label: string }> = [ { id: "file", label: "File" }, { id: "memory", label: "In memory" }, + { id: "ducklake", label: "DuckLake" }, { id: "url", label: "JDBC URL" }, ]; +const DUCKLAKE_CATALOGS: Array> = [ + { value: "file", label: "Catalog file" }, + { value: "secret", label: "DuckDB secret" }, +]; + const TYPES: SelectOption[] = VENDORS.map((v) => ({ value: v.id, label: v.label, icon: v.icon })); const COLORS: Array> = [ @@ -222,6 +230,13 @@ function jdbcDatabaseFile(file: string | null | undefined, root: string | undefi return `${directory.replace(/\/+$/, "")}/${path}`; } +function duckLakePath(path: string, root: string | undefined, projectRelative = false): string | null { + if (!path.trim() || /[\0\r\n]/.test(path) || path.startsWith("//") || path.startsWith("\\")) return null; + return absoluteDatabaseFile(path, root) || (projectRelative && root && !path.includes(":")) + ? jdbcDatabaseFile(path, root) + : null; +} + function builtInTarget(s: DataSource, driver: DataSource["driver"], root: string | undefined): Partial { const url = s.url ?? ""; if (driver === "sqlite") { @@ -289,6 +304,9 @@ function FileField({ value, placeholder, disabled, + invalid, + browseLabel, + directory = false, title, onChange, }: { @@ -297,6 +315,9 @@ function FileField({ value: string; placeholder?: string; disabled?: boolean; + invalid?: boolean; + browseLabel?: string; + directory?: boolean; title: string; onChange: (v: string) => void; }) { @@ -310,14 +331,16 @@ function FileField({ id={id} className={styles.fill} disabled={disabled} + invalid={invalid} value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} /> + + {jdbcProfile && !lakeDriver && ( + + DuckLake requires the official DuckDB JDBC driver. + + )} + + ) : ( + <> + + { + setUrlDraft(e.target.value); + setTest(null); + }} + /> + + )} {duckDbMemory && ( <> @@ -1458,8 +1627,8 @@ export function SourceDialog({
set({ readOnly })} label="Read-only" /> @@ -2163,7 +2332,9 @@ export function SourceDialog({ {busy && !shownTest ? busyKind === "external" ? tx("Testing external TCP tunnel and PostgreSQL connection…") - : tx("Connecting…") + : busyKind === "creatingLake" + ? tx("Creating DuckLake…") + : tx("Connecting…") : (externalError ?? shownTest?.text)} {shownTest?.trust && ( <> diff --git a/src/platform/i18n.test.ts b/src/platform/i18n.test.ts index 32851fc52c..017e7cb625 100644 --- a/src/platform/i18n.test.ts +++ b/src/platform/i18n.test.ts @@ -377,8 +377,9 @@ describe("catalogs", () => { "Deno", "Node.js", "bun-dap (Bun)", - // DuckDB data source: the product name, the JDBC URL field and its path placeholder. + // DuckDB and DuckLake product names, the JDBC URL field and its path placeholder. "DuckDB", + "DuckLake", "JDBC URL", "path/to/database.duckdb", // Unreal Engine projects: the product name and the .uproject path placeholder. diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 7ae85978c1..41066e96bc 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9416,6 +9416,30 @@ "Allowed command pattern": "允許的命令模式", "Blocked command pattern": "封鎖的命令模式", "Mode applies to": "模式作用範圍", + "DuckLake": "DuckLake", + "Catalog file": "目錄檔案", + "DuckDB secret": "DuckDB 金鑰", + "Catalog type:": "目錄類型:", + "Catalog type": "目錄類型", + "Catalog file:": "目錄檔案:", + "Open DuckLake Catalog": "開啟 DuckLake 目錄", + "Browse for DuckLake catalog": "瀏覽 DuckLake 目錄檔案", + "Secret name:": "金鑰名稱:", + "Choose an existing catalog file on the database host.": "請選擇資料庫主機上既有的目錄檔案。", + "Use the name of an existing DuckDB secret of type ducklake.": "請輸入既有的 ducklake 類型 DuckDB 金鑰名稱。", + "Data directory:": "資料目錄:", + "Choose DuckLake Data Directory": "選擇 DuckLake 資料目錄", + "Browse for DuckLake data directory": "瀏覽 DuckLake 資料目錄", + "Optional absolute directory on the database host. Leave empty to use the catalog’s stored location.": "選填。請指定資料庫主機上的絕對目錄。留空則使用目錄中記錄的儲存位置。", + "Create New DuckLake…": "建立 DuckLake…", + "Create New DuckLake": "建立 DuckLake", + "Choose a new DuckLake directory": "選擇新的 DuckLake 目錄", + "Choose an absolute directory on the database host.": "請選擇資料庫主機上的絕對目錄。", + "Create a DuckLake in '{directory}'? The directory must not already exist.": "要在「{directory}」中建立 DuckLake 嗎?此目錄必須尚未存在。", + "DuckLake created. The data source opens it read-only.": "已建立 DuckLake。資料來源會以唯讀方式開啟它。", + "DuckLake requires the official DuckDB JDBC driver.": "DuckLake 需要官方 DuckDB JDBC 驅動程式。", + "Update the remote OpenIDEA server to save DuckLake data sources.": "請更新遠端 OpenIDEA 伺服器以儲存 DuckLake 資料來源。", + "Creating DuckLake…": "正在建立 DuckLake…", "Allow all optional permissions": "允許全部可選權限", "Show Record View": "顯示記錄檢視", "Open in Value Editor": "在值編輯器中開啟", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 0b9a6b8cfb..82c29d3ce0 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -279,6 +279,30 @@ "Custom JDBC": "自定义 JDBC", "Data source type:": "数据源类型:", "DuckDB": "DuckDB", + "DuckLake": "DuckLake", + "Catalog file": "目录文件", + "DuckDB secret": "DuckDB 密钥", + "Catalog type:": "目录类型:", + "Catalog type": "目录类型", + "Catalog file:": "目录文件:", + "Open DuckLake Catalog": "打开 DuckLake 目录", + "Browse for DuckLake catalog": "浏览 DuckLake 目录文件", + "Secret name:": "密钥名称:", + "Choose an existing catalog file on the database host.": "请选择数据库主机上已有的目录文件。", + "Use the name of an existing DuckDB secret of type ducklake.": "请输入已有的 ducklake 类型 DuckDB 密钥名称。", + "Data directory:": "数据目录:", + "Choose DuckLake Data Directory": "选择 DuckLake 数据目录", + "Browse for DuckLake data directory": "浏览 DuckLake 数据目录", + "Optional absolute directory on the database host. Leave empty to use the catalog’s stored location.": "可选。请指定数据库主机上的绝对目录。留空则使用目录中记录的存储位置。", + "Create New DuckLake…": "新建 DuckLake…", + "Create New DuckLake": "新建 DuckLake", + "Choose a new DuckLake directory": "选择新的 DuckLake 目录", + "Choose an absolute directory on the database host.": "请选择数据库主机上的绝对目录。", + "Create a DuckLake in '{directory}'? The directory must not already exist.": "要在“{directory}”中新建 DuckLake 吗?该目录必须尚不存在。", + "DuckLake created. The data source opens it read-only.": "已创建 DuckLake。数据源将以只读方式打开它。", + "DuckLake requires the official DuckDB JDBC driver.": "DuckLake 需要官方 DuckDB JDBC 驱动。", + "Update the remote OpenIDEA server to save DuckLake data sources.": "请更新远程 OpenIDEA 服务器以保存 DuckLake 数据源。", + "Creating DuckLake…": "正在创建 DuckLake…", "In memory": "内存", "JDBC URL": "JDBC URL", "Passed to the DuckDB JDBC driver as connection properties.": "这些连接属性将传递给 DuckDB JDBC 驱动。",