//! Data sources: per-project connection settings in `.openidea/data-sources.toml`, and //! global ones (IDEA's Make Global: listed in every project) in `data-sources.toml` of the //! app data directory. Project folder grouping is in `.openidea/data-source-folders.toml`. //! Passwords never go there: saved ones live in [`crate::secrets`], //! the others only in memory for the session. use ide_core::{IdeError, IdeResult, IpcPath, project_dir}; use serde::{Deserialize, Serialize}; use specta::Type; 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)] #[serde(rename_all = "camelCase")] pub enum DbDriver { Sqlite, Postgres, /// MySQL and MariaDB. Mysql, /// Microsoft SQL Server. SqlServer, Clickhouse, /// Oracle Database (pure-Rust thin driver, no client library). Oracle, Snowflake, Jdbc, } impl DbDriver { pub fn default_port(self) -> Option { match self { DbDriver::Sqlite | DbDriver::Jdbc => None, DbDriver::Postgres => Some(5432), DbDriver::Mysql => Some(3306), DbDriver::SqlServer => Some(1433), DbDriver::Clickhouse => Some(8123), DbDriver::Oracle => Some(1521), DbDriver::Snowflake => Some(443), } } } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub enum DbSslMode { Disable, #[default] Prefer, Require, /// Require, and check the server certificate against the CA file. VerifyCa, /// [`DbSslMode::VerifyCa`], and check that the certificate names the host. VerifyFull, } /// IDEA's data source colours (tree node and console tab tint), e.g. red for production. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub enum DbColor { Red, Orange, Yellow, Green, Blue, Violet, } /// Transaction control of the data source's consoles. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub enum DbTxMode { #[default] Auto, Manual, } /// Options tab: session settings applied to every connection. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase", default)] pub struct DbOptions { pub transaction: DbTxMode, /// PostgreSQL `search_path` (unqualified names resolve there). pub default_schema: String, /// Session time zone (`TimeZone` / `time_zone`); empty keeps the default. pub time_zone: String, /// Statements run on every new connection. pub startup_script: String, /// Run `SELECT 1` this often while connected. pub keep_alive_secs: Option, /// Disconnect after this long without statements (enforced by the UI, which sees the activity). pub auto_disconnect_secs: Option, /// PostgreSQL: show only the configured database, its schemas right under the data source. pub single_database: bool, } /// Schemas tab: the databases / schemas the tree shows. Names may use `*` and `?`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase", default)] pub struct DbIntrospection { pub all_databases: bool, pub databases: Vec, pub all_schemas: bool, pub schemas: Vec, /// A database can replace the source's schema rules with all schemas or a list of exact names. #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub schemas_by_database: BTreeMap, /// `pg_catalog`, `information_schema`, `mysql`…, and service databases (`rdsadmin`…). pub show_system: bool, /// PostgreSQL template databases (`template0`, `template1`). pub show_templates: bool, /// Object filter: the tree lists only tables, views, routines and sequences matching /// one of these patterns (`*`, `?`; separated by commas or spaces). Empty: all. pub object_filter: String, } impl Default for DbIntrospection { fn default() -> Self { Self { all_databases: true, databases: Vec::new(), all_schemas: true, schemas: Vec::new(), schemas_by_database: BTreeMap::new(), show_system: false, show_templates: false, object_filter: String::new(), } } } impl DbIntrospection { pub(crate) fn with_visibility_from(self, source: &Self) -> Self { Self { all_databases: source.all_databases, databases: source.databases.clone(), all_schemas: source.all_schemas, schemas: source.schemas.clone(), schemas_by_database: source.schemas_by_database.clone(), object_filter: source.object_filter.clone(), ..self } } /// Whether the tree shows this schema: every one with `all_schemas`, otherwise it has to /// match one of the `schemas` patterns. The completion model uses the same test, so it /// offers exactly the tables the tree lists (and does not read the ones it never shows). pub fn shows_schema(&self, name: &str) -> bool { self.all_schemas || self.schemas.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).any(|p| schema_matches(p, name)) } } /// `*` matches any run of characters, `?` a single one; a pattern without wildcards matches the /// name as typed (the dialog fills names from the list the server returned, so case is settled). fn schema_matches(pattern: &str, name: &str) -> bool { if !pattern.contains('*') && !pattern.contains('?') { return pattern == name; } let p: Vec = pattern.chars().collect(); let n: Vec = name.chars().collect(); let (mut pi, mut ni) = (0, 0); // Position of the last `*` and how much of the name it has already swallowed. let mut star: Option<(usize, usize)> = None; while ni < n.len() { if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) { pi += 1; ni += 1; } else if pi < p.len() && p[pi] == '*' { star = Some((pi, ni)); pi += 1; } else if let Some((at, taken)) = star { pi = at + 1; ni = taken + 1; star = Some((at, taken + 1)); } else { return false; } } p[pi..].iter().all(|&c| c == '*') } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(default)] pub struct DbSchemaSelection { pub all: bool, pub names: Vec, } #[derive(Debug, Clone, Serialize, Deserialize, Type)] #[serde(tag = "kind", rename_all = "camelCase")] pub enum DbVisibilityChange { Databases { selection: DbSchemaSelection }, Schemas { selection: DbSchemaSelection }, DatabaseSchemas { database: String, selection: Option }, } impl DbVisibilityChange { pub(crate) fn apply(self, introspection: &mut DbIntrospection, available: &[String]) { let available: std::collections::HashSet<_> = available.iter().map(String::as_str).collect(); let keep_names = |before: &mut Vec, selection: DbSchemaSelection, exact: bool| { if selection.all || (!exact && before.iter().any(|name| name.contains(['*', '?']))) { return; } before.retain(|name| !available.contains(if exact { name.as_str() } else { name.trim() })); let mut seen: std::collections::HashSet<_> = before.iter().cloned().collect(); before.extend( selection .names .into_iter() .filter(|name| (exact || !name.contains(['*', '?'])) && seen.insert(name.clone())), ); }; match self { Self::Databases { selection } => { introspection.all_databases = selection.all; keep_names(&mut introspection.databases, selection, false); } Self::Schemas { selection } => { introspection.all_schemas = selection.all; keep_names(&mut introspection.schemas, selection, false); } Self::DatabaseSchemas { database, selection } => match selection { Some(selection) => { let rule = introspection.schemas_by_database.entry(database).or_default(); rule.all = selection.all; keep_names(&mut rule.names, selection, true); } None => { introspection.schemas_by_database.remove(&database); } }, } } } /// Advanced tab: a driver property. PostgreSQL: run-time parameters (and /// `application_name`); MySQL: session variables (and `charset`, `collation`); /// SQLite: pragmas. See [`crate::conn`]. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase", default)] pub struct DbProperty { pub name: String, pub value: String, } /// How a Snowflake data source signs in. The data source's one saved secret is what the /// method needs: the private key's passphrase, the password, or the token. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub enum DbSnowflakeAuth { /// RSA key pair: a JWT signed with the private key file. #[default] KeyPair, /// User name and password. Password, /// Programmatic access token. Token, /// OAuth access token. OAuth, /// Single sign-on in the web browser. Browser, } /// Snowflake connection settings beyond the shared ones: the account identifier is /// [`DataSource::host`], the schema [`DbOptions::default_schema`]. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase", default)] pub struct DbSnowflake { pub warehouse: String, pub role: String, pub auth: DbSnowflakeAuth, /// PEM private key of [`DbSnowflakeAuth::KeyPair`]; `~/` is the home directory. Only the /// path is stored: the key is read from the file at each login. pub private_key_file: String, } /// How the SSH tunnel authenticates (shared with Settings › SSH Configurations). pub use ide_core::remote_settings::SshAuth as DbSshAuth; /// Connect through an SSH tunnel: the database host and port are reached from `host`. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase", default)] pub struct DbSsh { pub enabled: bool, /// A Settings › SSH Configurations id to connect with; empty = the fields below. pub config: String, /// Host name, or a `Host` alias of `~/.ssh/config` with [`DbSshAuth::OpenSsh`]. pub host: String, pub port: Option, pub user: String, pub auth: DbSshAuth, /// Private key for [`DbSshAuth::KeyPair`]; `~/` is the home directory. pub key_file: String, /// Keep the SSH password / key passphrase in the saved passwords. pub save_secret: bool, } /// A foreground program that forwards an IDE-assigned loopback port to the database. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct DbExternalTunnel { pub executable: String, 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 { pub id: String, pub name: String, pub driver: DbDriver, /// An app-wide driver profile id; classpaths never come from a project. #[serde(skip_serializing_if = "String::is_empty")] pub jdbc_driver: String, pub host: String, pub port: Option, pub database: String, pub user: String, /// SQLite database file (absolute, or relative to the project root). pub file: Option, pub ssl: DbSslMode, /// Keep the password in the saved passwords. pub save_password: bool, /// Refuse statements other than queries (enforced by the database session where possible). pub read_only: bool, /// SSH tunnel settings (`None`: never configured; kept but unused when not `enabled`). pub ssh: Option, #[serde(skip_serializing_if = "Option::is_none")] pub external_tunnel: Option, /// Wire-compatible product preset (`cockroachdb`, `tidb`…; empty: the driver itself). pub vendor: String, pub color: Option, pub comment: String, /// Connect with [`DataSource::url`] instead of the host / port / database fields. pub url_only: bool, pub url: String, /// PEM files; `~/` is the home directory. pub ssl_ca_file: String, pub ssl_cert_file: String, pub ssl_key_file: String, pub options: DbOptions, pub introspection: DbIntrospection, 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, /// Plugin id owning this source; absent for user-managed sources. #[serde(skip_serializing_if = "Option::is_none")] pub plugin_owner: Option, /// Id private to the owner, never used as a connection target. #[serde(skip_serializing_if = "Option::is_none")] pub plugin_source_id: Option, } impl Default for DataSource { fn default() -> Self { Self { id: String::new(), name: String::new(), driver: DbDriver::Sqlite, jdbc_driver: String::new(), host: "localhost".into(), port: None, database: String::new(), user: String::new(), file: None, ssl: DbSslMode::Prefer, save_password: false, read_only: false, ssh: None, external_tunnel: None, vendor: String::new(), color: None, comment: String::new(), url_only: false, url: String::new(), ssl_ca_file: String::new(), ssl_cert_file: String::new(), ssl_key_file: String::new(), options: DbOptions::default(), introspection: DbIntrospection::default(), properties: Vec::new(), snowflake: None, duck_lake: None, global: false, plugin_owner: None, plugin_source_id: None, } } } /// The connection settings of a URL (`jdbc:` prefix allowed). #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ParsedUrl { pub driver: Option, pub host: String, pub port: Option, pub database: String, pub user: String, pub password: Option, /// Query parameters, in order. pub params: Vec<(String, String)>, /// SQLite file. pub file: Option, } fn percent_decode(s: &str) -> String { let b = s.as_bytes(); let mut out = Vec::with_capacity(b.len()); let mut i = 0; let hex = |i: usize| b.get(i).and_then(|&c| (c as char).to_digit(16)); while i < b.len() { if b[i] == b'%' && let (Some(h), Some(l)) = (hex(i + 1), hex(i + 2)) { out.push((h * 16 + l) as u8); i += 3; continue; } out.push(b[i]); i += 1; } String::from_utf8_lossy(&out).into_owned() } /// The driver speaking the protocol of URL scheme `scheme` (wire-compatible products included). pub fn scheme_driver(scheme: &str) -> Option { match scheme.to_ascii_lowercase().as_str() { "postgres" | "postgresql" | "pgsql" | "redshift" | "cockroachdb" | "cockroach" | "yugabytedb" | "timescaledb" | "greenplum" => Some(DbDriver::Postgres), "mysql" | "mariadb" | "tidb" | "singlestore" | "memsql" | "oceanbase" | "starrocks" => Some(DbDriver::Mysql), "sqlserver" | "mssql" | "mssqlserver" => Some(DbDriver::SqlServer), "sqlite" | "sqlite3" => Some(DbDriver::Sqlite), "clickhouse" | "http" | "https" => Some(DbDriver::Clickhouse), "oracle" | "oracledb" => Some(DbDriver::Oracle), "snowflake" => Some(DbDriver::Snowflake), _ => None, } } /// Parses `scheme://[user[:password]@]host[:port][/database][?k=v&…]`, `jdbc:` forms /// included, and `sqlite:path`. pub fn parse_url(raw: &str) -> IdeResult { let bad = || IdeError::invalid("invalid database URL"); let url = raw.trim(); let url = url.strip_prefix("jdbc:").or_else(|| url.strip_prefix("JDBC:")).unwrap_or(url); let (scheme, rest) = url.split_once(':').ok_or_else(bad)?; let driver = scheme_driver(scheme).ok_or_else(bad)?; // JDBC thin URLs: `jdbc:oracle:thin:@//host:port/service` (after the `jdbc:` prefix). let rest = if driver == DbDriver::Oracle { rest.strip_prefix("thin:@").or_else(|| rest.strip_prefix("thin:/@")).unwrap_or(rest) } else { rest }; if driver == DbDriver::Sqlite { let file = rest.strip_prefix("//").unwrap_or(rest); let file = file.split('?').next().unwrap_or_default(); if file.is_empty() { return Err(bad()); } return Ok(ParsedUrl { driver: Some(driver), file: Some(percent_decode(file)), ..Default::default() }); } let rest = rest.strip_prefix("//").ok_or_else(bad)?; let (main, query) = rest.split_once('?').unwrap_or((rest, "")); let (authority, database) = main.split_once('/').unwrap_or((main, "")); let (userinfo, hostport) = match authority.rsplit_once('@') { Some((u, h)) => (Some(u), h), None => (None, authority), }; // Several hosts (failover lists): the first. let hostport = hostport.split(',').next().unwrap_or_default(); let (host, port) = if let Some(v6) = hostport.strip_prefix('[') { let (h, after) = v6.split_once(']').ok_or_else(bad)?; (h.to_owned(), after.strip_prefix(':')) } else { match hostport.rsplit_once(':') { Some((h, p)) => (h.to_owned(), Some(p)), None => (hostport.to_owned(), None), } }; let port = match port.filter(|p| !p.is_empty()) { Some(p) => Some(p.parse::().map_err(|_| bad())?), None => None, }; let mut parsed = ParsedUrl { driver: Some(driver), host, port, database: percent_decode(database.trim_end_matches('/')), ..Default::default() }; if let Some(u) = userinfo { let (user, password) = match u.split_once(':') { Some((u, p)) => (u, Some(percent_decode(p))), None => (u, None), }; parsed.user = percent_decode(user); parsed.password = password; } for pair in query.split('&').filter(|p| !p.is_empty()) { let (k, v) = pair.split_once('=').unwrap_or((pair, "")); let (k, v) = (percent_decode(k), percent_decode(v)); match k.as_str() { "user" if parsed.user.is_empty() => parsed.user = v, "password" if parsed.password.is_none() => parsed.password = Some(v), _ => parsed.params.push((k, v)), } } 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. if self.driver == DbDriver::Snowflake && !self.database.eq_ignore_ascii_case(db) { self.options.default_schema.clear(); } self.database = db.to_owned(); } } pub(crate) fn same_except_visibility(&self, other: &Self) -> bool { if self == other { return true; } let introspection = other.introspection.clone().with_visibility_from(&self.introspection); *self == Self { introspection, ..other.clone() } } /// The settings to connect with: with [`DataSource::url_only`], host, port, /// 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:")); } return Ok(self.clone()); } if !self.url_only { return Ok(self.clone()); } let u = parse_url(&self.url)?; let mut s = self.clone(); if let Some(d) = u.driver && d != s.driver { return Err(IdeError::invalid(format!("the URL is not for the {:?} driver", s.driver))); } if s.driver == DbDriver::Sqlite { s.file = u.file.map(IpcPath::from); return Ok(s); } s.host = u.host; s.port = u.port; s.database = u.database; if !u.user.is_empty() { s.user = u.user; } let mut properties = Vec::new(); for (k, v) in u.params { if s.driver == DbDriver::Snowflake && s.snowflake_url_parameter(&k, &v) { continue; } match k.to_ascii_lowercase().as_str() { "sslmode" | "ssl-mode" => { s.ssl = match v.to_ascii_lowercase().replace('-', "_").as_str() { "disable" | "disabled" => DbSslMode::Disable, "require" | "required" => DbSslMode::Require, "verify_ca" => DbSslMode::VerifyCa, "verify_full" | "verify_identity" => DbSslMode::VerifyFull, _ => DbSslMode::Prefer, } } "sslrootcert" | "ssl-ca" | "sslca" => s.ssl_ca_file = v, "sslcert" | "ssl-cert" => s.ssl_cert_file = v, "sslkey" | "ssl-key" => s.ssl_key_file = v, _ => properties.push(DbProperty { name: k, value: v }), } } properties.append(&mut s.properties); s.properties = properties; if s.driver == DbDriver::Clickhouse { let raw_url = self.url.trim().to_ascii_lowercase(); let url = raw_url.strip_prefix("jdbc:").unwrap_or(&raw_url); if url.starts_with("https://") { s.ssl = DbSslMode::VerifyFull; } else if url.starts_with("http://") { s.ssl = DbSslMode::Disable; } } Ok(s) } /// Applies a parameter of a Snowflake JDBC URL that names a connection setting. fn snowflake_url_parameter(&mut self, name: &str, value: &str) -> bool { let settings = self.snowflake.get_or_insert_with(DbSnowflake::default); match name.to_ascii_lowercase().as_str() { "db" | "database" => self.database = value.to_owned(), "schema" => self.options.default_schema = value.to_owned(), "warehouse" => settings.warehouse = value.to_owned(), "role" => settings.role = value.to_owned(), "private_key_file" => settings.private_key_file = value.to_owned(), "authenticator" => { settings.auth = match value.to_ascii_lowercase().as_str() { "snowflake_jwt" => DbSnowflakeAuth::KeyPair, "externalbrowser" => DbSnowflakeAuth::Browser, "oauth" => DbSnowflakeAuth::OAuth, "programmatic_access_token" => DbSnowflakeAuth::Token, "snowflake" => DbSnowflakeAuth::Password, _ => return false, } } _ => return false, } true } /// The Snowflake settings (defaults when none were saved). pub fn snowflake(&self) -> DbSnowflake { self.snowflake.clone().unwrap_or_default() } /// The password written in the URL of a [`DataSource::url_only`] data source. pub fn url_password(&self) -> Option { if self.driver == DbDriver::Jdbc || !self.url_only { return None; } parse_url(&self.url).ok()?.password } } #[derive(Debug, Default, Serialize, Deserialize)] struct SourcesFile { #[serde(default, rename = "data-source")] sources: Vec, } /// The project's data sources. pub fn load(root: &Path) -> IdeResult> { let mut sources = read(&project_dir::path(root, FILE))?; for source in &mut sources { source.global = false; } Ok(sources) } /// Saves the project's data sources. pub fn save(root: &Path, sources: &[DataSource]) -> IdeResult<()> { write(&project_dir::path(root, FILE), sources) } /// The global data sources stored in `dir` (the app data directory). pub fn load_global(dir: &Path) -> IdeResult> { let mut sources = read(&dir.join(FILE))?; for s in &mut sources { s.global = true; } Ok(sources) } /// Saves the global data sources in `dir`. pub fn save_global(dir: &Path, sources: &[DataSource]) -> IdeResult<()> { write(&dir.join(FILE), sources) } fn read(path: &Path) -> IdeResult> { let text = match std::fs::read_to_string(path) { Ok(t) => t, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), Err(e) => return Err(e.into()), }; let file: SourcesFile = toml::from_str(&text).map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?; Ok(file.sources) } fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> { for s in sources { if s.id.is_empty() || s.name.trim().is_empty() { return Err(IdeError::invalid("every data source needs an id and a name")); } } if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; } let internal = |e: &dyn std::fmt::Display| IdeError::internal(e.to_string()); let mut value = toml::Value::try_from(SourcesFile { sources: sources.to_vec() }).map_err(|e| internal(&e))?; if let Some(list) = value.get_mut("data-source").and_then(toml::Value::as_array_mut) { for table in list.iter_mut().filter_map(toml::Value::as_table_mut) { table.remove("global"); } } std::fs::write(path, toml::to_string_pretty(&value).map_err(|e| internal(&e))?)?; Ok(()) } /// A user folder grouping data sources in one project's Database tree. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct DbSourceFolder { pub id: String, pub name: String, /// Reserved for nested folders; the first UI version only creates root folders. #[serde(default, skip_serializing_if = "Option::is_none")] pub parent: Option, pub order: i32, pub sources: Vec, } #[derive(Debug, Serialize, Deserialize)] struct SourceFoldersFile { #[serde(default = "folders_version")] version: u32, #[serde(default, rename = "folder")] folders: Vec, } fn folders_version() -> u32 { 1 } /// The project's data source folders and their members. pub fn load_folders(root: &Path) -> IdeResult> { let path = project_dir::path(root, FOLDERS_FILE); let text = match std::fs::read_to_string(&path) { Ok(text) => text, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), Err(e) => return Err(e.into()), }; let file: SourceFoldersFile = toml::from_str(&text).map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?; if file.version > 1 { return Err(IdeError::invalid(format!( "{}: folder format version {} is newer than this OpenIDEA", path.display(), file.version ))); } Ok(file.folders) } /// Replaces the project's data source folders after validating ids, parents and memberships. pub fn save_folders(root: &Path, folders: &[DbSourceFolder]) -> IdeResult<()> { validate_folders(folders)?; let path = project_dir::path(root, FOLDERS_FILE); if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; } let file = SourceFoldersFile { version: folders_version(), folders: folders.to_vec() }; let text = toml::to_string_pretty(&file).map_err(|e| IdeError::internal(e.to_string()))?; let tmp = path.with_file_name(format!(".{FOLDERS_FILE}.{}.tmp", uuid::Uuid::new_v4())); std::fs::write(&tmp, text)?; if let Err(e) = std::fs::rename(&tmp, &path) { let _ = std::fs::remove_file(&tmp); return Err(e.into()); } Ok(()) } fn validate_folders(folders: &[DbSourceFolder]) -> IdeResult<()> { let mut ids = HashSet::new(); let mut members = HashSet::new(); for folder in folders { if folder.id.trim().is_empty() || folder.name.trim().is_empty() { return Err(IdeError::invalid("every data source folder needs an id and a name")); } if !ids.insert(folder.id.as_str()) { return Err(IdeError::invalid(format!("duplicate data source folder id '{}'", folder.id))); } for source in &folder.sources { if source.is_empty() { return Err(IdeError::invalid(format!("folder '{}' has an empty data source id", folder.name))); } if !members.insert(source.as_str()) { return Err(IdeError::invalid(format!("data source '{source}' belongs to more than one folder"))); } } } for folder in folders { let mut seen = HashSet::new(); let mut parent = folder.parent.as_deref(); while let Some(id) = parent { if id == folder.id || !seen.insert(id) { return Err(IdeError::invalid(format!("data source folder '{}' has a parent cycle", folder.name))); } parent = folders.iter().find(|candidate| candidate.id == id).and_then(|candidate| candidate.parent.as_deref()); if parent.is_none() && !folders.iter().any(|candidate| candidate.id == id) { return Err(IdeError::invalid(format!( "data source folder '{}' has an unknown parent '{id}'", folder.name ))); } } } Ok(()) } /// Credential store access. Blocking (may show an OS prompt): call off the async runtime. /// Keys are data source ids; [`secrets::ssh_key`] names the SSH password / passphrase. #[cfg(test)] mod tests { use super::*; #[test] fn round_trips_without_passwords() { let tmp = tempfile::tempdir().unwrap(); assert!(load(tmp.path()).unwrap().is_empty()); let s = DataSource { id: "a1".into(), name: "local".into(), driver: DbDriver::Postgres, port: Some(5433), database: "app".into(), user: "me".into(), save_password: true, ..Default::default() }; save(tmp.path(), std::slice::from_ref(&s)).unwrap(); let text = std::fs::read_to_string(tmp.path().join(".openidea/data-sources.toml")).unwrap(); assert!(!text.contains("password ="), "{text}"); assert_eq!(load(tmp.path()).unwrap(), vec![s]); assert!(save(tmp.path(), &[DataSource::default()]).is_err()); } #[test] fn source_folders_round_trip_and_reject_invalid_memberships() { let tmp = tempfile::tempdir().unwrap(); let folders = vec![ DbSourceFolder { id: "prod".into(), name: "Production".into(), parent: None, order: 0, sources: vec!["pg".into(), "mysql".into()], }, DbSourceFolder { id: "empty".into(), name: "Empty".into(), parent: None, order: 1, sources: vec![] }, ]; save_folders(tmp.path(), &folders).unwrap(); assert_eq!(load_folders(tmp.path()).unwrap(), folders); let duplicate = vec![ DbSourceFolder { sources: vec!["pg".into()], ..folders[0].clone() }, DbSourceFolder { id: "other".into(), sources: vec!["pg".into()], ..folders[1].clone() }, ]; assert!(save_folders(tmp.path(), &duplicate).is_err()); let cycle = vec![ DbSourceFolder { parent: Some("b".into()), ..folders[0].clone() }, DbSourceFolder { id: "b".into(), parent: Some("prod".into()), ..folders[1].clone() }, ]; assert!(save_folders(tmp.path(), &cycle).is_err()); let missing = vec![DbSourceFolder { parent: Some("missing".into()), ..folders[0].clone() }]; assert!(save_folders(tmp.path(), &missing).is_err()); } #[test] fn reads_configs_written_before_the_new_settings() { let tmp = tempfile::tempdir().unwrap(); let dir = tmp.path().join(".openidea"); std::fs::create_dir_all(&dir).unwrap(); std::fs::write( dir.join(FILE), "[[data-source]]\nid = \"a\"\nname = \"old\"\ndriver = \"postgres\"\nhost = \"db\"\nssl = \"require\"\n", ) .unwrap(); let s = load(tmp.path()).unwrap().remove(0); assert_eq!(s.ssl, DbSslMode::Require); assert!(s.introspection.all_databases && s.introspection.all_schemas); assert_eq!((s.color, s.url_only, s.options.transaction), (None, false, DbTxMode::Auto)); } #[test] fn round_trips_the_new_settings() { let tmp = tempfile::tempdir().unwrap(); let s = DataSource { id: "b".into(), name: "prod".into(), driver: DbDriver::Mysql, vendor: "tidb".into(), color: Some(DbColor::Red), comment: "careful".into(), ssl: DbSslMode::VerifyFull, ssl_ca_file: "~/ca.pem".into(), options: DbOptions { time_zone: "UTC".into(), keep_alive_secs: Some(60), ..Default::default() }, introspection: DbIntrospection { all_schemas: false, schemas: vec!["app*".into()], ..Default::default() }, properties: vec![DbProperty { name: "sql_mode".into(), value: "ANSI".into() }], ..Default::default() }; save(tmp.path(), std::slice::from_ref(&s)).unwrap(); assert_eq!(load(tmp.path()).unwrap(), vec![s]); } #[test] fn visibility_change_preserves_patterns_unavailable_names_and_other_scopes() { let mut introspection = DbIntrospection { schemas: vec!["app_*".into(), "unavailable_?".into()], databases: vec!["reporting".into(), "offline".into()], schemas_by_database: BTreeMap::from([ ("reporting".into(), DbSchemaSelection { all: false, names: vec!["private".into()] }), ("sandbox".into(), DbSchemaSelection { all: false, names: vec!["experiments".into()] }), ]), show_system: true, ..Default::default() }; DbVisibilityChange::Schemas { selection: DbSchemaSelection { all: false, names: vec!["demo".into()] } } .apply(&mut introspection, &["app_sales".into(), "demo".into()]); assert_eq!(introspection.schemas, ["app_*", "unavailable_?"]); DbVisibilityChange::Databases { selection: DbSchemaSelection { all: false, names: vec!["sandbox".into()] } } .apply(&mut introspection, &["reporting".into(), "sandbox".into()]); assert_eq!(introspection.databases, ["offline", "sandbox"]); DbVisibilityChange::DatabaseSchemas { database: "reporting".into(), selection: Some(DbSchemaSelection { all: false, names: vec!["finance".into(), "finance".into(), "private".into()], }), } .apply(&mut introspection, &["public".into(), "finance".into()]); assert_eq!(introspection.schemas_by_database["reporting"].names, ["private", "finance"]); assert_eq!(introspection.schemas_by_database["sandbox"].names, ["experiments"]); assert!(introspection.show_system); } #[test] fn schema_override_can_omit_default_fields() { let introspection: DbIntrospection = toml::from_str( r#" [schemasByDatabase.reporting] all = true [schemasByDatabase.sandbox] names = ["finance"] "#, ) .unwrap(); assert_eq!( introspection.schemas_by_database, BTreeMap::from([ ("reporting".into(), DbSchemaSelection { all: true, names: vec![] }), ("sandbox".into(), DbSchemaSelection { all: false, names: vec!["finance".into()] }), ]) ); } #[test] fn round_trips_database_schema_overrides() { let tmp = tempfile::tempdir().unwrap(); let source = DataSource { id: "postgres".into(), name: "PostgreSQL Demo".into(), driver: DbDriver::Postgres, introspection: DbIntrospection { all_schemas: false, schemas: vec!["app_*".into()], schemas_by_database: BTreeMap::from([ ("analytics".into(), DbSchemaSelection { all: true, names: vec![] }), ("reporting.eu".into(), DbSchemaSelection { all: false, names: vec!["public".into()] }), ("sandbox".into(), DbSchemaSelection { all: false, names: vec![] }), ]), ..Default::default() }, ..Default::default() }; save(tmp.path(), std::slice::from_ref(&source)).unwrap(); assert_eq!(load(tmp.path()).unwrap(), vec![source]); } #[test] fn sqlserver_defaults() { assert_eq!(DbDriver::SqlServer.default_port(), Some(1433)); assert_eq!(scheme_driver("sqlserver"), Some(DbDriver::SqlServer)); assert_eq!(scheme_driver("mssql"), Some(DbDriver::SqlServer)); assert_eq!(scheme_driver("mssqlserver"), Some(DbDriver::SqlServer)); } #[test] fn parses_urls() { let u = parse_url("jdbc:postgresql://ann:s%40cret@db.local:5433/shop?sslmode=require&search_path=app").unwrap(); assert_eq!(u.driver, Some(DbDriver::Postgres)); assert_eq!((u.host.as_str(), u.port, u.database.as_str()), ("db.local", Some(5433), "shop")); assert_eq!((u.user.as_str(), u.password.as_deref()), ("ann", Some("s@cret"))); assert_eq!(u.params, vec![("sslmode".into(), "require".into()), ("search_path".into(), "app".into())]); let u = parse_url("mysql://[::1]/app?user=root").unwrap(); assert_eq!((u.host.as_str(), u.port, u.user.as_str()), ("::1", None, "root")); assert_eq!(parse_url("jdbc:redshift://r:5439/dev").unwrap().driver, Some(DbDriver::Postgres)); assert_eq!(parse_url("tidb://h:4000").unwrap().driver, Some(DbDriver::Mysql)); assert_eq!(parse_url("starrocks://h:9030").unwrap().driver, Some(DbDriver::Mysql)); assert_eq!(parse_url("sqlite:/tmp/a.db").unwrap().file.as_deref(), Some("/tmp/a.db")); let u = parse_url("oracle://scott:tiger@db.local:1521/ORCLPDB1").unwrap(); assert_eq!(u.driver, Some(DbDriver::Oracle)); assert_eq!((u.host.as_str(), u.port, u.database.as_str()), ("db.local", Some(1521), "ORCLPDB1")); assert_eq!((u.user.as_str(), u.password.as_deref()), ("scott", Some("tiger"))); assert_eq!(parse_url("oracledb://hr@db.local/hrdb").unwrap().driver, Some(DbDriver::Oracle)); assert!(parse_url("postgres://h:99999/db").is_err()); } #[test] fn url_only_sources_connect_with_the_url() { let s = DataSource { driver: DbDriver::Postgres, user: "fallback".into(), url_only: true, url: "postgres://ann:pw@h:6543/app?sslmode=verify-full&sslrootcert=/ca.pem&statement_timeout=5000".into(), properties: vec![DbProperty { name: "work_mem".into(), value: "64MB".into() }], ..Default::default() }; let r = s.resolved().unwrap(); assert_eq!((r.host.as_str(), r.port, r.database.as_str(), r.user.as_str()), ("h", Some(6543), "app", "ann")); assert_eq!((r.ssl, r.ssl_ca_file.as_str()), (DbSslMode::VerifyFull, "/ca.pem")); let names: Vec<_> = r.properties.iter().map(|p| p.name.as_str()).collect(); assert_eq!(names, ["statement_timeout", "work_mem"]); assert_eq!(s.url_password().as_deref(), Some("pw")); assert!(DataSource { url: "mysql://h/db".into(), ..s.clone() }.resolved().is_err()); assert_eq!(DataSource { url_only: false, ..s }.resolved().unwrap().host, "localhost"); } #[test] fn clickhouse_urls_resolve_http_https_and_credentials() { assert_eq!(DbDriver::Clickhouse.default_port(), Some(8123)); let source = DataSource { driver: DbDriver::Clickhouse, url_only: true, url: "https://reader:s%40cret@db.example:8443/analytics?max_execution_time=30".into(), ..Default::default() }; let resolved = source.resolved().unwrap(); assert_eq!(resolved.host, "db.example"); assert_eq!(resolved.port, Some(8443)); assert_eq!(resolved.database, "analytics"); assert_eq!(resolved.user, "reader"); assert_eq!(resolved.ssl, DbSslMode::VerifyFull); assert_eq!(source.url_password().as_deref(), Some("s@cret")); assert_eq!(resolved.properties[0].name, "max_execution_time"); let http = DataSource { url: "http://localhost/default".into(), ..source.clone() }.resolved().unwrap(); assert_eq!(http.ssl, DbSslMode::Disable); let jdbc = DataSource { url: "jdbc:clickhouse://localhost/analytics".into(), ..source.clone() }; assert_eq!(jdbc.resolved().unwrap().database, "analytics"); let secure = DataSource { url: "https://db.example/default?sslmode=disable".into(), ..source }; assert_eq!(secure.resolved().unwrap().ssl, DbSslMode::VerifyFull); let error = parse_url("clickhouse://reader:secret@db.example:invalid/default").unwrap_err(); assert!(!error.message.contains("secret")); } #[test] fn snowflake_settings_round_trip_and_stay_out_of_other_sources() { let tmp = tempfile::tempdir().unwrap(); let snowflake = DataSource { id: "sf".into(), name: "warehouse".into(), driver: DbDriver::Snowflake, host: "myorg-myaccount".into(), user: "jane".into(), database: "ANALYTICS".into(), save_password: true, snowflake: Some(DbSnowflake { warehouse: "COMPUTE_WH".into(), role: "ANALYST".into(), auth: DbSnowflakeAuth::KeyPair, private_key_file: "~/.ssh/rsa_key.p8".into(), }), ..Default::default() }; let other = DataSource { id: "pg".into(), name: "pg".into(), driver: DbDriver::Postgres, ..Default::default() }; save(tmp.path(), &[snowflake.clone(), other.clone()]).unwrap(); assert_eq!(load(tmp.path()).unwrap(), vec![snowflake, other]); let text = std::fs::read_to_string(project_dir::path(tmp.path(), FILE)).unwrap(); assert_eq!(text.matches("snowflake]").count(), 1, "{text}"); assert!(text.contains("driver = \"snowflake\""), "{text}"); assert!(text.contains("auth = \"keyPair\""), "{text}"); assert!(text.contains("privateKeyFile = \"~/.ssh/rsa_key.p8\""), "{text}"); assert_eq!(DbDriver::Snowflake.default_port(), Some(443)); assert_eq!(DataSource::default().snowflake(), DbSnowflake::default()); } #[test] fn snowflake_jdbc_urls_name_the_session_settings() { let s = DataSource { driver: DbDriver::Snowflake, url_only: true, url: "jdbc:snowflake://myorg-myaccount.snowflakecomputing.com:443/?warehouse=COMPUTE_WH&db=ANALYTICS\ &schema=PUBLIC&role=ANALYST&user=jane&authenticator=snowflake_jwt\ &private_key_file=%7E%2Fkeys%2Frsa_key.p8&QUERY_TAG=ide" .into(), ..Default::default() }; let r = s.resolved().unwrap(); assert_eq!(r.host, "myorg-myaccount.snowflakecomputing.com"); assert_eq!(r.port, Some(443)); assert_eq!(r.user, "jane"); assert_eq!(r.database, "ANALYTICS"); assert_eq!(r.options.default_schema, "PUBLIC"); assert_eq!( r.snowflake(), DbSnowflake { warehouse: "COMPUTE_WH".into(), role: "ANALYST".into(), auth: DbSnowflakeAuth::KeyPair, private_key_file: "~/keys/rsa_key.p8".into(), } ); assert_eq!(r.properties, vec![DbProperty { name: "QUERY_TAG".into(), value: "ide".into() }]); let browser = DataSource { url: "snowflake://xy12345.eu-central-1.snowflakecomputing.com/DB?authenticator=externalbrowser".into(), ..s }; let r = browser.resolved().unwrap(); assert_eq!(r.database, "DB"); assert_eq!(r.snowflake().auth, DbSnowflakeAuth::Browser); assert_eq!(scheme_driver("snowflake"), Some(DbDriver::Snowflake)); } #[test] fn introspection_shows_only_the_picked_schemas() { let mut i = DbIntrospection::default(); assert!(i.shows_schema("SYS"), "the default reads every schema"); i.all_schemas = false; assert!(!i.shows_schema("SYS"), "nothing picked: the tree lists nothing either"); i.schemas = vec!["XMCB".into(), " APP_* ".into()]; assert!(i.shows_schema("XMCB")); assert!(i.shows_schema("APP_INFO")); assert!(!i.shows_schema("APP"), "`*` needs the text that follows it"); assert!(!i.shows_schema("SYS")); assert!(!i.shows_schema("xmcb"), "patterns match the names the server returned"); i.schemas = vec!["?".into()]; assert!(i.shows_schema("A")); assert!(!i.shows_schema("AB")); } }