diff --git a/crates/ide-db/src/jdbc/mod.rs b/crates/ide-db/src/jdbc/mod.rs
index 8e973fb7f..e58a7f2eb 100644
--- a/crates/ide-db/src/jdbc/mod.rs
+++ b/crates/ide-db/src/jdbc/mod.rs
@@ -22,6 +22,9 @@ const LIMIT: usize = 16 * 1024 * 1024;
pub struct DbJdbcDriver {
pub id: String,
pub name: String,
+ /// Data source preset id; absent for a generic JDBC profile.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub vendor: Option,
pub jars: Vec,
pub class_name: String,
pub url_template: String,
@@ -146,7 +149,7 @@ impl DbManager {
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(&(
+ let mut settings = serde_json::to_vec(&(
&source.jdbc_driver,
&source.url,
&source.user,
@@ -155,6 +158,9 @@ impl DbManager {
&source.options,
))
.map_err(|e| IdeError::internal(e.to_string()))?;
+ if self.jdbc_password_isolated(source) {
+ settings.extend_from_slice(b"\0jdbc-password");
+ }
Ok((
registry.with_file_name("jdbc-approvals").join(blake3::hash(&key).to_hex().as_str()),
blake3::hash(&settings).to_hex().to_string(),
@@ -195,6 +201,9 @@ impl DbManager {
.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"));
+ }
JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc"))
.await
.map(Box::new)
diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs
index bbd858b03..cc3cb6753 100644
--- a/crates/ide-db/src/lib.rs
+++ b/crates/ide-db/src/lib.rs
@@ -475,6 +475,29 @@ impl DbManager {
}
}
+ fn non_password_snowflake(source: &DataSource) -> Option {
+ let settings = match source.driver {
+ DbDriver::Snowflake => source.resolved().map(|source| source.snowflake()).unwrap_or_default(),
+ DbDriver::Jdbc => source.snowflake.clone()?,
+ _ => return None,
+ };
+ (settings.auth != DbSnowflakeAuth::Password).then_some(settings)
+ }
+
+ fn jdbc_password_isolated(&self, source: &DataSource) -> bool {
+ source.driver == DbDriver::Jdbc
+ && (Self::non_password_snowflake(source).is_some()
+ || self
+ .sources()
+ .unwrap_or_default()
+ .iter()
+ .any(|stored| stored.id == source.id && Self::non_password_snowflake(stored).is_some()))
+ }
+
+ fn password_key(&self, source: &DataSource) -> String {
+ if self.jdbc_password_isolated(source) { secrets::jdbc_key(&source.id) } else { source.id.clone() }
+ }
+
/// The connection settings of target `target` ([`DataSource::resolved`]), with
/// its database for `:`.
pub fn source(&self, target: &str) -> IdeResult {
@@ -497,13 +520,19 @@ impl DbManager {
/// Saves the data source list; connections of removed or changed sources are closed.
/// Global ones (`global`) go to the app-wide list, the others to the project's.
- pub async fn save_sources(&self, sources: Vec) -> IdeResult<()> {
+ pub async fn save_sources(&self, mut sources: Vec) -> IdeResult<()> {
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) {
+ // 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);
+ }
+ }
let (global, project): (Vec<_>, Vec<_>) = sources.iter().cloned().partition(|s| s.global);
match &self.global {
// Rewritten only when it changes: other projects' windows edit the same file.
@@ -524,7 +553,8 @@ impl DbManager {
match sources.iter().find(|s| s.id == o.id) {
Some(n) if *n == o => {}
gone_or_changed => {
- let keys = [o.id.clone(), secrets::ssh_key(&o.id), Self::sso_credential(&o.id)];
+ let keys =
+ [o.id.clone(), secrets::jdbc_key(&o.id), secrets::ssh_key(&o.id), Self::sso_credential(&o.id)];
match gone_or_changed {
None => {
self.catalogs.forget(&o.id);
@@ -590,7 +620,12 @@ impl DbManager {
/// Remembers `password` for the session, and in the saved passwords when
/// the data source saves passwords (`None` forgets it).
pub async fn set_password(&self, id: &str, password: Option, save: bool) -> IdeResult<()> {
- self.remember(id, id.to_owned(), password, save).await
+ let source = self.sources()?.into_iter().find(|s| s.id == id);
+ let (store, key) = match source.as_ref() {
+ Some(source) => (self.store_of(source), self.password_key(source)),
+ None => (&self.saved_passwords, id.to_owned()),
+ };
+ self.remember(store, key, password, save).await
}
/// [`DbManager::set_password`] for the SSH password / key passphrase.
@@ -602,10 +637,10 @@ impl DbManager {
self.ssh.set_secret(&c, secret, save);
return Ok(());
}
- self.remember(id, secrets::ssh_key(id), secret, save).await
+ self.remember(self.saved_for(id), secrets::ssh_key(id), secret, save).await
}
- async fn remember(&self, id: &str, key: String, secret: Option, save: bool) -> IdeResult<()> {
+ async fn remember(&self, store: &SecretStore, key: String, secret: Option, save: bool) -> IdeResult<()> {
match &secret {
Some(p) => {
self.session_passwords.lock().insert(key.clone(), p.clone());
@@ -614,7 +649,6 @@ impl DbManager {
self.session_passwords.lock().remove(&key);
}
}
- let store = self.saved_for(id);
let result = match (secret, save) {
(Some(p), true) => store.set(&key, &p),
_ => {
@@ -640,7 +674,10 @@ impl DbManager {
}
async fn password(&self, source: &DataSource) -> Option {
- match self.secret(source, source.id.clone(), source.driver != DbDriver::Sqlite && source.save_password).await {
+ match self
+ .secret(source, self.password_key(source), source.driver != DbDriver::Sqlite && source.save_password)
+ .await
+ {
Some(p) => Some(p),
None => source.url_password(),
}
@@ -1763,6 +1800,78 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn switching_from_snowflake_key_pair_keeps_the_jdbc_password_separate() -> IdeResult<()> {
+ let tmp = tempfile::tempdir()?;
+ let db = manager(tmp.path()).with_global_sources(tmp.path().join("global"));
+ let native = DataSource {
+ id: "snowflake".into(),
+ name: "Snowflake".into(),
+ driver: DbDriver::Snowflake,
+ save_password: true,
+ url_only: true,
+ url: "jdbc:snowflake://example.invalid/?authenticator=SNOWFLAKE_JWT".into(),
+ ..Default::default()
+ };
+ db.save_sources(vec![native.clone()]).await?;
+ db.set_password(&native.id, Some("native-passphrase".into()), true).await?;
+ let jdbc = DataSource { driver: DbDriver::Jdbc, url: "jdbc:fixture:".into(), ..native.clone() };
+
+ // Test Connection can use the JDBC draft before the user saves it.
+ assert_eq!(db.password(&jdbc).await, None);
+ assert_eq!(db.password(&native).await.as_deref(), Some("native-passphrase"));
+
+ db.approve_jdbc_source(&jdbc)?;
+ db.save_sources(vec![jdbc.clone()]).await?;
+ assert_eq!(db.password(&db.source(&jdbc.id)?).await, None);
+ db.set_password(&jdbc.id, Some("jdbc-password".into()), true).await?;
+ let reopened = manager(tmp.path()).with_global_sources(tmp.path().join("global"));
+ let saved = reopened.source(&jdbc.id)?;
+ assert_eq!(reopened.password(&saved).await.as_deref(), Some("jdbc-password"));
+ let err = reopened.pool(&jdbc.id).await.err().expect("no JDBC profile installed");
+ assert!(err.message.contains("Select an installed JDBC driver profile"));
+
+ source::save(&reopened.root, std::slice::from_ref(&jdbc))?;
+ let err = reopened.pool(&jdbc.id).await.err().expect("edited settings need approval");
+ assert!(err.message.contains("Review this project's JDBC URL and properties"));
+ source::save(&reopened.root, std::slice::from_ref(&saved))?;
+
+ let global = DataSource { global: true, ..saved };
+ reopened.save_sources(vec![global.clone()]).await?;
+ assert_eq!(reopened.password(&reopened.source(&jdbc.id)?).await.as_deref(), Some("jdbc-password"));
+
+ let native = DataSource { global: true, ..native };
+ reopened.save_sources(vec![native.clone()]).await?;
+ assert_eq!(reopened.password(&native).await.as_deref(), Some("native-passphrase"));
+ reopened.save_sources(Vec::new()).await?;
+ assert_eq!(reopened.password(&native).await, None);
+ assert_eq!(reopened.password(&global).await, None);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn switching_from_snowflake_password_keeps_the_password() -> IdeResult<()> {
+ let tmp = tempfile::tempdir()?;
+ let db = manager(tmp.path());
+ let native = DataSource {
+ id: "snowflake".into(),
+ name: "Snowflake".into(),
+ driver: DbDriver::Snowflake,
+ save_password: true,
+ url_only: true,
+ url: "jdbc:snowflake://example.invalid/?authenticator=snowflake".into(),
+ ..Default::default()
+ };
+ db.save_sources(vec![native.clone()]).await?;
+ db.set_password(&native.id, Some("existing-password".into()), true).await?;
+ let jdbc = DataSource { driver: DbDriver::Jdbc, url: "jdbc:fixture:".into(), ..native };
+ assert_eq!(db.password(&jdbc).await.as_deref(), Some("existing-password"));
+ db.save_sources(vec![jdbc.clone()]).await?;
+ let reopened = manager(tmp.path());
+ assert_eq!(reopened.password(&reopened.source(&jdbc.id)?).await.as_deref(), Some("existing-password"));
+ Ok(())
+ }
+
#[tokio::test]
async fn moves_plaintext_passwords_of_older_versions_off_disk() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/crates/ide-db/src/secrets.rs b/crates/ide-db/src/secrets.rs
index 9889232a6..73aaa0899 100644
--- a/crates/ide-db/src/secrets.rs
+++ b/crates/ide-db/src/secrets.rs
@@ -18,6 +18,11 @@ pub fn ssh_key(id: &str) -> String {
format!("{id}#ssh")
}
+/// JDBC password when the original credential is a Snowflake passphrase or token.
+pub fn jdbc_key(id: &str) -> String {
+ format!("{id}#jdbc")
+}
+
fn file_key(project: &str, key: &str) -> String {
format!("{project}|{key}")
}
diff --git a/crates/ide-db/tests/jdbc.rs b/crates/ide-db/tests/jdbc.rs
index 29387948e..9fff39921 100644
--- a/crates/ide-db/tests/jdbc.rs
+++ b/crates/ide-db/tests/jdbc.rs
@@ -17,12 +17,14 @@ async fn jdbc_profiles_persist_and_project_files_cannot_start_drivers() -> IdeRe
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Test".into(),
+ vendor: None,
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");
+ assert_eq!(reopened.jdbc_drivers()?[0].vendor, None);
let source = DataSource {
id: "local".into(),
name: "local".into(),
@@ -53,6 +55,40 @@ async fn jdbc_profiles_persist_and_project_files_cannot_start_drivers() -> IdeRe
Ok(())
}
+#[tokio::test]
+async fn named_jdbc_sources_persist_the_type_and_reject_a_profile_for_another_type() -> 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(),
+ vendor: Some("tidb".into()),
+ jars: vec![jar.display().to_string()],
+ class_name: "test.Driver".into(),
+ url_template: String::new(),
+ })?;
+ let source = DataSource {
+ id: "local".into(),
+ name: "local".into(),
+ driver: DbDriver::Jdbc,
+ vendor: "mariadb".into(),
+ jdbc_driver: "fixture".into(),
+ url: "jdbc:test:".into(),
+ ..Default::default()
+ };
+ db.save_sources(vec![source]).await?;
+ let reopened = manager(tmp.path());
+ let source = reopened.source("local")?;
+ assert_eq!(reopened.jdbc_drivers()?[0].vendor.as_deref(), Some("tidb"));
+ assert_eq!(source.driver, DbDriver::Jdbc);
+ assert_eq!(source.vendor, "mariadb");
+ let err = reopened.test(&source, None, None).await.unwrap_err();
+ assert!(err.message.contains("not associated with this data source type"));
+ Ok(())
+}
+
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
@@ -63,6 +99,7 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
db.save_jdbc_driver(DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
+ vendor: None,
jars: vec![jar],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
@@ -135,6 +172,7 @@ async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> {
db.save_jdbc_driver(DbJdbcDriver {
id: "clickhouse".into(),
name: "ClickHouse JDBC".into(),
+ vendor: Some("clickhouse".into()),
jars,
class_name: "com.clickhouse.jdbc.ClickHouseDriver".into(),
url_template: "jdbc:clickhouse://".into(),
@@ -143,6 +181,7 @@ async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> {
id: "test".into(),
name: "ClickHouse JDBC".into(),
driver: DbDriver::Jdbc,
+ vendor: "clickhouse".into(),
jdbc_driver: "clickhouse".into(),
url: format!("jdbc:clickhouse://127.0.0.1:{port}/default"),
user: "fixture".into(),
@@ -181,6 +220,7 @@ async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> {
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Fixture".into(),
+ vendor: None,
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
url_template: String::new(),
@@ -229,6 +269,7 @@ async fn a_lost_session_reconnects_on_the_next_statement() -> IdeResult<()> {
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Fixture".into(),
+ vendor: None,
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
url_template: String::new(),
diff --git a/docs/en/guide/database.mdx b/docs/en/guide/database.mdx
index 3a7a6cd47..641c864f6 100644
--- a/docs/en/guide/database.mdx
+++ b/docs/en/guide/database.mdx
@@ -23,9 +23,13 @@ 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
+## 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.
+In a named data source's **General** tab, **Driver** defaults to **Built-in**. 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.
+
+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.
+
+When switching to JDBC, configure TLS and driver-specific settings in the JDBC URL or **Advanced** properties. If the built-in source used an SSH tunnel, configure an equivalent route for the JDBC connection. JDBC uses auto-commit. Review the built-in startup script, default schema, and time zone, and configure equivalent settings supported by your JDBC driver or database. For enforced read-only access, use a database account with read-only privileges. Enter a separate JDBC password when converting a Snowflake source that used key pair, token, or browser authentication and your JDBC driver needs a password.
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.
diff --git a/docs/zh/guide/database.mdx b/docs/zh/guide/database.mdx
index 063031f9e..bab3ec91c 100644
--- a/docs/zh/guide/database.mdx
+++ b/docs/zh/guide/database.mdx
@@ -23,9 +23,13 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行
预设会填好默认端口,必要时还会设置 SSL(例如 Redshift、Neon 和 Supabase 要求 SSL)。
-## 自定义 JDBC 驱动
+## JDBC 驱动
-选择 **新建 › 数据源 › 自定义 JDBC**,然后选择 **管理驱动…**。为驱动配置命名,添加厂商提供的驱动 JAR 及依赖 JAR,填写完整的驱动类名和可选的 JDBC URL 模板。请仅导入可信来源的驱动。OpenIDEA 使用已安装的 Java 17 或更高版本运行时在单独的进程中加载驱动。 IDE 会读取 JAR 声明的驱动类,也支持手动输入完整类名。URL 模板支持 `{host}`、`{port}`、`{database}` 和 `{file}`,也可直接填写 JDBC URL。 URL 和高级属性会写入数据源配置,密码请填在密码栏,以使用系统凭据存储。“只读”选项会请求 JDBC 驱动建立只读连接。使用具备只读权限的数据库账号可强制限制写入。取消查询时,如果驱动停止了语句,会话及其临时表会保留。如果驱动在三秒内未响应,OpenIDEA 会关闭该会话。已提交的语句仍可能在服务器上完成。
+在预设数据源的 **常规** 选项卡中,**驱动** 默认为 **内置**。通过 **管理驱动…** 查看或添加该数据源类型的 JDBC 驱动配置。在 **驱动** 中选中配置后,数据源会使用 JDBC,同时保留原有类型及图标。选择 **转到驱动** 可查看所选配置及其 JAR 文件。对于没有预设的数据库,请选择 **新建 › 数据源 › 自定义 JDBC**。也可以在其中选择 **管理驱动…** 查看所有配置并修改关联类型。
+
+为驱动配置命名,添加厂商提供的驱动 JAR 及依赖 JAR,填写完整的驱动类名和可选的 JDBC URL 模板。请仅导入可信来源的驱动。OpenIDEA 使用已安装的 Java 17 或更高版本运行时在单独的进程中加载驱动。 IDE 会读取 JAR 声明的驱动类,也支持手动输入完整类名。URL 模板支持 `{host}`、`{port}`、`{database}` 和 `{file}`,也可直接填写 JDBC URL。 URL 和高级属性会写入数据源配置,密码请填在密码栏,以使用系统凭据存储。“只读”选项会请求 JDBC 驱动建立只读连接。使用具备只读权限的数据库账号可强制限制写入。取消查询时,如果驱动停止了语句,会话及其临时表会保留。如果驱动在三秒内未响应,OpenIDEA 会关闭该会话。已提交的语句仍可能在服务器上完成。
+
+切换到 JDBC 时,请在 JDBC URL 或 **高级** 属性中配置 TLS 和驱动专用设置。如果内置数据源使用了 SSH 隧道,请为 JDBC 连接配置等效的网络路径。JDBC 使用自动提交。请检查内置驱动的启动脚本、默认模式和时区,并通过 JDBC 驱动或数据库配置相应的设置。要强制限制为只读访问,请使用具备只读权限的数据库账号。如果原 Snowflake 数据源使用密钥对、令牌或浏览器认证,且 JDBC 驱动需要密码,请单独设置 JDBC 密码。
选择驱动配置,填写厂商的 JDBC URL,在 **用户**、**密码** 和 **高级** 中设置凭据和驱动属性。通过密码字段输入的密码可以保存到系统凭据库。在 Linux 上,保存密码需要正在运行的 Secret Service;也可以仅为当前会话输入密码。**测试连接** 显示数据库产品和版本。可以通过 JDBC 元数据浏览模式、表和列,在 SQL 控制台中查询或以自动提交方式更新数据。自定义驱动不支持厂商特有的 DDL、执行计划或表格编辑。
diff --git a/e2e/jdbc-source.spec.ts b/e2e/jdbc-source.spec.ts
index 94da49c41..ca52768a0 100644
--- a/e2e/jdbc-source.spec.ts
+++ b/e2e/jdbc-source.spec.ts
@@ -1,10 +1,20 @@
import type { DataSource_Deserialize, DbJdbcDriver } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
-test("configures a local JDBC profile and a source through mocked IPC", async ({ workbench: page }, info) => {
+test("uses a local JDBC profile for a named data source through mocked IPC", async ({ workbench: page }, info) => {
await stubDesktop(page);
await page.evaluate(async () => {
- const drivers: Record[] = [];
+ const drivers: Record[] = [
+ { id: "sqlite-fixture", vendor: "sqlite", name: "SQLite JDBC" },
+ { id: "postgres-fixture", vendor: "postgres", name: "PostgreSQL JDBC" },
+ { id: "legacy-fixture", name: "Legacy JDBC" },
+ { id: "clickhouse-fixture", vendor: "clickhouse", name: "Existing ClickHouse JDBC" },
+ ].map((driver) => ({
+ ...driver,
+ jars: [`/mock/${driver.id}.jar`],
+ className: "org.example.jdbc.Driver",
+ urlTemplate: "jdbc:example:local",
+ }));
let sources: Record[] = [];
Object.assign(window.__ipc.handlers, {
db_jdbc_drivers: () => drivers,
@@ -48,20 +58,30 @@ test("configures a local JDBC profile and a source through mocked IPC", async ({
});
});
const source = page.getByRole("dialog", { name: "New Data Source", exact: true });
+ await source.screenshot({
+ path: info.outputPath("mock-native-clickhouse-general.png"),
+ animations: "disabled",
+ });
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 expect(source.getByRole("button", { name: "Connection driver", exact: true })).toHaveText("Built-in");
await source.getByRole("button", { name: "Manage Drivers…", exact: true }).click();
const profiles = page.getByRole("dialog", { name: "JDBC Driver Profiles", exact: true });
+ const profilesPicker = profiles.getByRole("button", { name: "JDBC driver profiles", exact: true });
+ await profilesPicker.click();
+ const choices = page.getByRole("listbox").getByRole("option");
+ await expect(choices).toHaveText(["Existing ClickHouse JDBC"]);
+ await page.screenshot({ path: info.outputPath("jdbc-manage-drivers-dropdown.png"), animations: "disabled" });
+ await page.getByRole("option", { name: "Existing ClickHouse JDBC", exact: true }).click();
await profiles.getByRole("button", { name: "Add…", exact: true }).click();
const editor = page.getByRole("dialog", { name: "Add JDBC Driver", exact: true });
+ const typePicker = editor.getByRole("button", { name: "Data source type", exact: true });
+ await expect(typePicker).toHaveText("ClickHouse");
+ await expect(typePicker).toBeDisabled();
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();
@@ -75,9 +95,11 @@ test("configures a local JDBC profile and a source through mocked IPC", async ({
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(
+ await expect(source.getByRole("button", { name: "Connection driver", exact: true })).toHaveText(
"Example local driver",
);
+ await expect(source.getByRole("button", { name: "Data source type", exact: true })).toHaveText("ClickHouse");
+ await expect(source.getByRole("tab", { name: "SSH/SSL", exact: true })).toHaveCount(0);
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");
@@ -108,6 +130,7 @@ test("configures a local JDBC profile and a source through mocked IPC", async ({
password: "mock secret",
source: {
driver: "jdbc",
+ vendor: "clickhouse",
url,
user: "example-user",
readOnly: true,
@@ -122,6 +145,22 @@ test("configures a local JDBC profile and a source through mocked IPC", async ({
const driver = profile?.driver as DbJdbcDriver | undefined;
if (!saved || !driver) throw new Error("Expected the JDBC source and driver to be saved");
expect(saved.readOnly).toBe(true);
+ expect(driver.vendor).toBe("clickhouse");
+ expect(saved.vendor).toBe("clickhouse");
expect(saved.jdbcDriver).toBe(driver.id);
for (const key of ["jars", "className", "classpath", "exec", "password"]) expect(saved).not.toHaveProperty(key);
+
+ 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: Mock connection", exact: true });
+ await expect(reopened.getByRole("button", { name: "Data source type", exact: true })).toHaveText("ClickHouse");
+ await reopened.getByRole("button", { name: "Go to Driver", exact: true }).click();
+ await expect(profilesPicker).toHaveText("Example local driver");
+ await expect(profiles.getByText("dependency.jar", { exact: true })).toBeVisible();
+ await profilesPicker.click();
+ await expect(choices).toHaveText(["Existing ClickHouse JDBC", "Example local driver"]);
+ await page.screenshot({ path: info.outputPath("jdbc-go-to-driver-dropdown.png"), animations: "disabled" });
});
diff --git a/src/bindings.ts b/src/bindings.ts
index ada66b549..0f64c75ab 100644
--- a/src/bindings.ts
+++ b/src/bindings.ts
@@ -338,7 +338,7 @@ export const commands = {
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")),
+ 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 })),
@@ -348,7 +348,7 @@ export const commands = {
* 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 })),
+ dbSaveJdbcDriver: (driver: DbJdbcDriver_Deserialize) => 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[],
@@ -4625,9 +4625,23 @@ export type DbIntrospection = {
objectFilter?: string,
};
-export type DbJdbcDriver = {
+export type DbJdbcDriver = DbJdbcDriver_Serialize | DbJdbcDriver_Deserialize;
+
+export type DbJdbcDriver_Deserialize = {
id: string,
name: string,
+ /** Data source preset id; absent for a generic JDBC profile. */
+ vendor?: string | null,
+ jars: string[],
+ className: string,
+ urlTemplate: string,
+};
+
+export type DbJdbcDriver_Serialize = {
+ id: string,
+ name: string,
+ /** Data source preset id; absent for a generic JDBC profile. */
+ vendor?: string | null,
jars: string[],
className: string,
urlTemplate: string,
diff --git a/src/features/database/JdbcDriverProfiles.tsx b/src/features/database/JdbcDriverProfiles.tsx
index af00b342a..f093c619a 100644
--- a/src/features/database/JdbcDriverProfiles.tsx
+++ b/src/features/database/JdbcDriverProfiles.tsx
@@ -4,20 +4,14 @@ import { useTx } from "@/platform/i18n";
import { Button, Dialog, IconButton, Input, Select, T } from "@/ui";
import { baseName } from "./dumpTools";
import { newSourceId } from "./model";
+import { VENDORS, vendorById } from "./vendors";
import styles from "./Database.module.css";
-export function useJdbcDrivers(enabled: boolean) {
+export function useJdbcDrivers() {
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) => {
@@ -30,7 +24,7 @@ export function useJdbcDrivers(enabled: boolean) {
return () => {
active = false;
};
- }, [enabled, attempt]);
+ }, [attempt]);
const retry = () => {
setDrivers(null);
setError(null);
@@ -41,9 +35,15 @@ export function useJdbcDrivers(enabled: boolean) {
const blankDriver = (): DbJdbcDriver => ({ id: newSourceId(), name: "", jars: [], className: "", urlTemplate: "" });
+const DRIVER_TYPES = [
+ { value: "", label: "Custom JDBC only" },
+ ...VENDORS.filter((v) => v.driver !== "jdbc").map((v) => ({ value: v.id, label: v.label, icon: v.icon })),
+];
+
export function JdbcDriverProfiles({
drivers,
selected,
+ sourceVendor,
onSave,
onUse,
onRemove,
@@ -51,21 +51,24 @@ export function JdbcDriverProfiles({
}: {
drivers: DbJdbcDriver[];
selected: string;
+ sourceVendor?: string;
onSave: (driver: DbJdbcDriver) => void;
onUse?: (driver: DbJdbcDriver) => void;
onRemove: (id: string) => void;
onClose: () => void;
}) {
const tx = useTx();
+ const profiles = sourceVendor ? drivers.filter((d) => d.vendor === sourceVendor) : drivers;
const [selection, setSelection] = useState(
- drivers.some((d) => d.id === selected) ? selected : (drivers[0]?.id ?? ""),
+ profiles.some((d) => d.id === selected) ? selected : (profiles[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 current = profiles.find((d) => d.id === selection);
+ const changedType = draft && profiles.some((d) => d.id === draft.id && d.vendor && d.vendor !== draft.vendor);
const name = current?.name ?? "";
const set = (patch: Partial) => setDraft((d) => d && { ...d, ...patch });
const classValid =
@@ -107,7 +110,12 @@ export function JdbcDriverProfiles({
if (!draft || !valid || busy) return;
setBusy(true);
setError(null);
- const driver = { ...draft, name: draft.name.trim(), className: draft.className.trim() };
+ const driver = {
+ ...draft,
+ ...(sourceVendor && { vendor: sourceVendor }),
+ name: draft.name.trim(),
+ className: draft.className.trim(),
+ };
try {
await call(commands.dbSaveJdbcDriver(driver));
onSave(driver);
@@ -129,7 +137,7 @@ export function JdbcDriverProfiles({
try {
await call(commands.dbRemoveJdbcDriver(current.id));
onRemove(current.id);
- setSelection(drivers.find((d) => d.id !== current.id)?.id ?? "");
+ setSelection(profiles.find((d) => d.id !== current.id)?.id ?? "");
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
@@ -144,7 +152,7 @@ export function JdbcDriverProfiles({
open
title={
draft
- ? drivers.some((d) => d.id === draft.id)
+ ? profiles.some((d) => d.id === draft.id)
? "Edit JDBC Driver"
: "Add JDBC Driver"
: "JDBC Driver Profiles"
@@ -184,6 +192,16 @@ export function JdbcDriverProfiles({
disabled={busy}
onChange={(e) => set({ name: e.target.value })}
/>
+
+ Data source type:
+
+
+ {confirm === "trust" && changedType && (
+
+
+ Sources that use this profile for its previous type will need a matching profile the next time they
+ connect, including sources in other projects.
+
+