| 1 | //! 连接串解析。一个输入框、四种 scheme;这里把 URL 拆成各引擎要的字段。 |
| 2 | //! |
| 3 | //! 写法沿用 `postgres://user:pass@host/db` 的形状:凭据在 userinfo 里,HTTP 族的 |
| 4 | //! 令牌放 password 位(`databricks://:TOKEN@…`),路径是「目录 / 库 / schema」, |
| 5 | //! 引擎特有的开关走 query。`ssl=false` 让 HTTP 族走明文——给本地代理与测试用, |
| 6 | //! 线上的三家都只认 https。 |
| 7 | |
| 8 | use percent_encoding::percent_decode_str; |
| 9 | use url::Url; |
| 10 | |
| 11 | fn decode(s: &str) -> String { |
| 12 | percent_decode_str(s).decode_utf8_lossy().into_owned() |
| 13 | } |
| 14 | |
| 15 | fn query(u: &Url, key: &str) -> Option<String> { |
| 16 | u.query_pairs() |
| 17 | .find(|(k, _)| k == key) |
| 18 | .map(|(_, v)| v.into_owned()) |
| 19 | .filter(|v| !v.is_empty()) |
| 20 | } |
| 21 | |
| 22 | fn ssl_off(u: &Url) -> bool { |
| 23 | matches!( |
| 24 | query(u, "ssl").as_deref(), |
| 25 | Some("false") | Some("0") | Some("off") | Some("no") |
| 26 | ) |
| 27 | } |
| 28 | |
| 29 | fn segments(u: &Url) -> Vec<String> { |
| 30 | u.path_segments() |
| 31 | .map(|s| s.filter(|x| !x.is_empty()).map(decode).collect()) |
| 32 | .unwrap_or_default() |
| 33 | } |
| 34 | |
| 35 | /// 令牌:password 位优先;没有 password 时 username 位也算(`databricks://TOKEN@host` |
| 36 | /// 少打一个冒号是最常见的手滑);最后看 `?token=` |
| 37 | fn token_of(u: &Url) -> Option<String> { |
| 38 | u.password() |
| 39 | .map(decode) |
| 40 | .filter(|s| !s.is_empty()) |
| 41 | .or_else(|| Some(decode(u.username())).filter(|s| !s.is_empty())) |
| 42 | .or_else(|| query(u, "token")) |
| 43 | } |
| 44 | |
| 45 | fn base_of(u: &Url, https: bool, default_port: u16) -> anyhow::Result<String> { |
| 46 | let host = u |
| 47 | .host_str() |
| 48 | .ok_or_else(|| anyhow::anyhow!("{}://: a host is required", u.scheme()))?; |
| 49 | let port = u.port().unwrap_or(default_port); |
| 50 | let scheme = if https { "https" } else { "http" }; |
| 51 | // 默认端口不写进 URL:reqwest 照样能连,日志里也干净 |
| 52 | let explicit = match (https, port) { |
| 53 | (true, 443) | (false, 80) => String::new(), |
| 54 | _ => format!(":{port}"), |
| 55 | }; |
| 56 | Ok(format!("{scheme}://{host}{explicit}")) |
| 57 | } |
| 58 | |
| 59 | /// `trino://user[:password]@host[:port]/[catalog[/schema]][?ssl=true|false]` |
| 60 | /// |
| 61 | /// 明文 http 是 Trino 的默认(8080);带密码、`ssl=true`、或端口 443 / 8443 时走 https—— |
| 62 | /// Trino 自己也拒绝在明文上收密码。`presto://` 是同一个协议的旧名。 |
| 63 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 64 | pub struct TrinoConn { |
| 65 | pub base: String, |
| 66 | pub user: String, |
| 67 | pub password: Option<String>, |
| 68 | pub catalog: Option<String>, |
| 69 | pub schema: Option<String>, |
| 70 | } |
| 71 | |
| 72 | impl TrinoConn { |
| 73 | pub fn parse(conn: &str) -> anyhow::Result<Self> { |
| 74 | let u = Url::parse(conn.trim())?; |
| 75 | let user = decode(u.username()); |
| 76 | if user.is_empty() { |
| 77 | anyhow::bail!("trino://: a user is required (it becomes X-Trino-User), e.g. trino://alice@host:8080/hive/default"); |
| 78 | } |
| 79 | let password = u.password().map(decode).filter(|s| !s.is_empty()); |
| 80 | let https = !ssl_off(&u) |
| 81 | && (password.is_some() |
| 82 | || query(&u, "ssl").as_deref() == Some("true") |
| 83 | || matches!(u.port(), Some(443) | Some(8443))); |
| 84 | let base = base_of(&u, https, if https { 443 } else { 8080 })?; |
| 85 | let segs = segments(&u); |
| 86 | Ok(Self { |
| 87 | base, |
| 88 | user, |
| 89 | password, |
| 90 | catalog: segs.first().cloned(), |
| 91 | schema: segs.get(1).cloned(), |
| 92 | }) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /// `databricks://:TOKEN@workspace-host/sql/1.0/warehouses/WAREHOUSE_ID[?catalog=main&schema=default]` |
| 97 | /// |
| 98 | /// 路径就是 JDBC 里的 httpPath,从控制台复制过来不用改;`?warehouse=ID` 也认。 |
| 99 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 100 | pub struct DatabricksConn { |
| 101 | pub base: String, |
| 102 | pub token: String, |
| 103 | pub warehouse_id: String, |
| 104 | pub catalog: Option<String>, |
| 105 | pub schema: Option<String>, |
| 106 | } |
| 107 | |
| 108 | impl DatabricksConn { |
| 109 | pub fn parse(conn: &str) -> anyhow::Result<Self> { |
| 110 | let u = Url::parse(conn.trim())?; |
| 111 | let base = base_of(&u, !ssl_off(&u), if ssl_off(&u) { 80 } else { 443 })?; |
| 112 | let token = token_of(&u).ok_or_else(|| { |
| 113 | anyhow::anyhow!("databricks://: a personal access token is required, e.g. databricks://:TOKEN@host/sql/1.0/warehouses/ID") |
| 114 | })?; |
| 115 | let segs = segments(&u); |
| 116 | let from_path = segs |
| 117 | .iter() |
| 118 | .position(|s| s == "warehouses") |
| 119 | .and_then(|i| segs.get(i + 1).cloned()); |
| 120 | let warehouse_id = query(&u, "warehouse").or(from_path).ok_or_else(|| { |
| 121 | anyhow::anyhow!("databricks://: a SQL warehouse is required — the /sql/1.0/warehouses/ID path or ?warehouse=ID") |
| 122 | })?; |
| 123 | Ok(Self { |
| 124 | base, |
| 125 | token, |
| 126 | warehouse_id, |
| 127 | catalog: query(&u, "catalog"), |
| 128 | schema: query(&u, "schema"), |
| 129 | }) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | /// `snowflake://:TOKEN@account.snowflakecomputing.com/[DATABASE[/SCHEMA]][?warehouse=WH&role=R&token_type=pat|oauth]` |
| 134 | /// |
| 135 | /// SQL API 不收密码,只收令牌:默认当作 programmatic access token,`token_type=oauth` |
| 136 | /// 换成 OAuth 令牌。密钥对 JWT 要本地签名,这一版不做。 |
| 137 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 138 | pub struct SnowflakeConn { |
| 139 | pub base: String, |
| 140 | pub token: String, |
| 141 | /// `X-Snowflake-Authorization-Token-Type` 的值 |
| 142 | pub token_type: &'static str, |
| 143 | pub database: Option<String>, |
| 144 | pub schema: Option<String>, |
| 145 | pub warehouse: Option<String>, |
| 146 | pub role: Option<String>, |
| 147 | } |
| 148 | |
| 149 | impl SnowflakeConn { |
| 150 | pub fn parse(conn: &str) -> anyhow::Result<Self> { |
| 151 | let u = Url::parse(conn.trim())?; |
| 152 | let base = base_of(&u, !ssl_off(&u), if ssl_off(&u) { 80 } else { 443 })?; |
| 153 | let token = token_of(&u).ok_or_else(|| { |
| 154 | anyhow::anyhow!("snowflake://: a programmatic access token or OAuth token is required, e.g. snowflake://:TOKEN@account.snowflakecomputing.com/DB/SCHEMA?warehouse=WH") |
| 155 | })?; |
| 156 | let token_type = match query(&u, "token_type") |
| 157 | .as_deref() |
| 158 | .map(str::to_ascii_lowercase) |
| 159 | .as_deref() |
| 160 | { |
| 161 | None | Some("pat") | Some("programmatic_access_token") => "PROGRAMMATIC_ACCESS_TOKEN", |
| 162 | Some("oauth") => "OAUTH", |
| 163 | Some(other) => { |
| 164 | anyhow::bail!("snowflake://: unknown token_type '{other}' (pat or oauth)") |
| 165 | } |
| 166 | }; |
| 167 | let segs = segments(&u); |
| 168 | Ok(Self { |
| 169 | base, |
| 170 | token, |
| 171 | token_type, |
| 172 | database: segs.first().cloned(), |
| 173 | schema: segs.get(1).cloned(), |
| 174 | warehouse: query(&u, "warehouse"), |
| 175 | role: query(&u, "role"), |
| 176 | }) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | #[cfg(test)] |
| 181 | mod tests { |
| 182 | use super::{DatabricksConn, SnowflakeConn, TrinoConn}; |
| 183 | |
| 184 | #[test] |
| 185 | fn trino_defaults_to_plain_http_and_upgrades_when_it_must() { |
| 186 | let c = TrinoConn::parse("trino://alice@lake.internal:8080/iceberg/sales").unwrap(); |
| 187 | assert_eq!(c.base, "http://lake.internal:8080"); |
| 188 | assert_eq!(c.user, "alice"); |
| 189 | assert_eq!(c.catalog.as_deref(), Some("iceberg")); |
| 190 | assert_eq!(c.schema.as_deref(), Some("sales")); |
| 191 | |
| 192 | let c = TrinoConn::parse("trino://alice:s%40cret@lake.internal/hive").unwrap(); |
| 193 | assert_eq!(c.base, "https://lake.internal"); |
| 194 | assert_eq!(c.password.as_deref(), Some("s@cret")); |
| 195 | |
| 196 | let c = TrinoConn::parse("trino://alice@lake.internal:8443/hive").unwrap(); |
| 197 | assert_eq!(c.base, "https://lake.internal:8443"); |
| 198 | |
| 199 | let c = TrinoConn::parse("presto://bob@127.0.0.1:9000?ssl=false").unwrap(); |
| 200 | assert_eq!(c.base, "http://127.0.0.1:9000"); |
| 201 | assert_eq!(c.catalog, None); |
| 202 | |
| 203 | assert!(TrinoConn::parse("trino://lake.internal/hive").is_err()); |
| 204 | } |
| 205 | |
| 206 | #[test] |
| 207 | fn databricks_reads_the_http_path_from_the_console() { |
| 208 | let c = DatabricksConn::parse( |
| 209 | "databricks://:dapi123@dbc-abc.cloud.databricks.com/sql/1.0/warehouses/9f2a?catalog=main&schema=sales", |
| 210 | ) |
| 211 | .unwrap(); |
| 212 | assert_eq!(c.base, "https://dbc-abc.cloud.databricks.com"); |
| 213 | assert_eq!(c.token, "dapi123"); |
| 214 | assert_eq!(c.warehouse_id, "9f2a"); |
| 215 | assert_eq!(c.catalog.as_deref(), Some("main")); |
| 216 | assert_eq!(c.schema.as_deref(), Some("sales")); |
| 217 | |
| 218 | let c = DatabricksConn::parse("databricks://dapi123@host?warehouse=w1").unwrap(); |
| 219 | assert_eq!(c.token, "dapi123"); |
| 220 | assert_eq!(c.warehouse_id, "w1"); |
| 221 | |
| 222 | assert!(DatabricksConn::parse("databricks://host/sql/1.0/warehouses/w1").is_err()); |
| 223 | assert!(DatabricksConn::parse("databricks://:t@host").is_err()); |
| 224 | } |
| 225 | |
| 226 | #[test] |
| 227 | fn snowflake_takes_a_token_and_the_session_knobs() { |
| 228 | let c = SnowflakeConn::parse( |
| 229 | "snowflake://:tok@xy12345.eu-central-1.snowflakecomputing.com/ANALYTICS/PUBLIC?warehouse=WH&role=ANALYST", |
| 230 | ) |
| 231 | .unwrap(); |
| 232 | assert_eq!( |
| 233 | c.base, |
| 234 | "https://xy12345.eu-central-1.snowflakecomputing.com" |
| 235 | ); |
| 236 | assert_eq!(c.token, "tok"); |
| 237 | assert_eq!(c.token_type, "PROGRAMMATIC_ACCESS_TOKEN"); |
| 238 | assert_eq!(c.database.as_deref(), Some("ANALYTICS")); |
| 239 | assert_eq!(c.schema.as_deref(), Some("PUBLIC")); |
| 240 | assert_eq!(c.warehouse.as_deref(), Some("WH")); |
| 241 | assert_eq!(c.role.as_deref(), Some("ANALYST")); |
| 242 | |
| 243 | let c = |
| 244 | SnowflakeConn::parse("snowflake://:tok@acct.snowflakecomputing.com?token_type=oauth") |
| 245 | .unwrap(); |
| 246 | assert_eq!(c.token_type, "OAUTH"); |
| 247 | assert!(SnowflakeConn::parse( |
| 248 | "snowflake://:tok@acct.snowflakecomputing.com?token_type=jwt" |
| 249 | ) |
| 250 | .is_err()); |
| 251 | assert!(SnowflakeConn::parse("snowflake://acct.snowflakecomputing.com/DB").is_err()); |
| 252 | } |
| 253 | } |