| 1 | //! Databricks SQL Statement Execution API(`/api/2.0/sql/statements`)。 |
| 2 | //! 一个 SQL warehouse 后面是 Unity Catalog 的整个湖仓(Delta 为主), |
| 3 | //! 令牌是 personal access token。结果要 INLINE + JSON_ARRAY:值全是字符串, |
| 4 | //! 按 manifest 里的列类型还原成数与布尔。 |
| 5 | |
| 6 | use super::conn::DatabricksConn; |
| 7 | use super::{ |
| 8 | coerce, rows_to_json_lines, sql_literal, truncate_rows, wrap_limit, QueryEngine, QueryResult, |
| 9 | SchemaColumn, HTTP_POLL_BUDGET, ROW_CAP, |
| 10 | }; |
| 11 | use serde::Deserialize; |
| 12 | use serde_json::json; |
| 13 | use std::time::{Duration, Instant}; |
| 14 | |
| 15 | pub struct DatabricksEngine { |
| 16 | conn: DatabricksConn, |
| 17 | } |
| 18 | |
| 19 | #[derive(Deserialize)] |
| 20 | struct StatementResponse { |
| 21 | statement_id: Option<String>, |
| 22 | status: Status, |
| 23 | manifest: Option<Manifest>, |
| 24 | result: Option<ResultData>, |
| 25 | } |
| 26 | |
| 27 | #[derive(Deserialize)] |
| 28 | struct Status { |
| 29 | state: String, |
| 30 | error: Option<StatusError>, |
| 31 | } |
| 32 | |
| 33 | #[derive(Deserialize)] |
| 34 | struct StatusError { |
| 35 | message: Option<String>, |
| 36 | error_code: Option<String>, |
| 37 | } |
| 38 | |
| 39 | #[derive(Deserialize)] |
| 40 | struct Manifest { |
| 41 | schema: Option<Schema>, |
| 42 | } |
| 43 | |
| 44 | #[derive(Deserialize)] |
| 45 | struct Schema { |
| 46 | columns: Vec<ColumnInfo>, |
| 47 | } |
| 48 | |
| 49 | #[derive(Deserialize)] |
| 50 | struct ColumnInfo { |
| 51 | name: String, |
| 52 | type_text: Option<String>, |
| 53 | } |
| 54 | |
| 55 | #[derive(Deserialize)] |
| 56 | struct ResultData { |
| 57 | data_array: Option<Vec<Vec<serde_json::Value>>>, |
| 58 | } |
| 59 | |
| 60 | impl DatabricksEngine { |
| 61 | pub fn new(conn: DatabricksConn) -> Self { |
| 62 | Self { conn } |
| 63 | } |
| 64 | |
| 65 | async fn run(&self, sql: &str) -> anyhow::Result<(Vec<String>, Vec<Vec<serde_json::Value>>)> { |
| 66 | let client = super::http()?; |
| 67 | let mut body = json!({ |
| 68 | "warehouse_id": self.conn.warehouse_id, |
| 69 | "statement": sql, |
| 70 | "wait_timeout": "30s", |
| 71 | "on_wait_timeout": "CONTINUE", |
| 72 | "disposition": "INLINE", |
| 73 | "format": "JSON_ARRAY", |
| 74 | "row_limit": ROW_CAP + 1, |
| 75 | }); |
| 76 | if let Some(c) = &self.conn.catalog { |
| 77 | body["catalog"] = json!(c); |
| 78 | } |
| 79 | if let Some(s) = &self.conn.schema { |
| 80 | body["schema"] = json!(s); |
| 81 | } |
| 82 | let mut resp: StatementResponse = client |
| 83 | .post(format!("{}/api/2.0/sql/statements", self.conn.base)) |
| 84 | .bearer_auth(&self.conn.token) |
| 85 | .json(&body) |
| 86 | .send() |
| 87 | .await? |
| 88 | .error_for_status()? |
| 89 | .json() |
| 90 | .await?; |
| 91 | let started = Instant::now(); |
| 92 | loop { |
| 93 | match resp.status.state.as_str() { |
| 94 | "SUCCEEDED" => break, |
| 95 | "PENDING" | "RUNNING" => { |
| 96 | let id = resp |
| 97 | .statement_id |
| 98 | .clone() |
| 99 | .ok_or_else(|| anyhow::anyhow!("Databricks returned no statement_id"))?; |
| 100 | if started.elapsed() > HTTP_POLL_BUDGET { |
| 101 | anyhow::bail!( |
| 102 | "Databricks statement did not finish within {}s", |
| 103 | HTTP_POLL_BUDGET.as_secs() |
| 104 | ); |
| 105 | } |
| 106 | tokio::time::sleep(Duration::from_secs(1)).await; |
| 107 | resp = client |
| 108 | .get(format!("{}/api/2.0/sql/statements/{id}", self.conn.base)) |
| 109 | .bearer_auth(&self.conn.token) |
| 110 | .send() |
| 111 | .await? |
| 112 | .error_for_status()? |
| 113 | .json() |
| 114 | .await?; |
| 115 | } |
| 116 | other => { |
| 117 | let e = resp.status.error.as_ref(); |
| 118 | let code = e |
| 119 | .and_then(|e| e.error_code.clone()) |
| 120 | .map(|c| format!("{c}: ")) |
| 121 | .unwrap_or_default(); |
| 122 | let msg = e |
| 123 | .and_then(|e| e.message.clone()) |
| 124 | .unwrap_or_else(|| format!("statement ended in state {other}")); |
| 125 | anyhow::bail!("{code}{msg}"); |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | let columns: Vec<ColumnInfo> = resp |
| 130 | .manifest |
| 131 | .and_then(|m| m.schema) |
| 132 | .map(|s| s.columns) |
| 133 | .unwrap_or_default(); |
| 134 | let raw_rows = resp.result.and_then(|r| r.data_array).unwrap_or_default(); |
| 135 | let rows = raw_rows |
| 136 | .into_iter() |
| 137 | .map(|row| { |
| 138 | row.iter() |
| 139 | .enumerate() |
| 140 | .map(|(i, v)| { |
| 141 | let ty = columns |
| 142 | .get(i) |
| 143 | .and_then(|c| c.type_text.as_deref()) |
| 144 | .unwrap_or(""); |
| 145 | coerce(ty, v) |
| 146 | }) |
| 147 | .collect() |
| 148 | }) |
| 149 | .collect(); |
| 150 | Ok((columns.into_iter().map(|c| c.name).collect(), rows)) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | #[async_trait::async_trait] |
| 155 | impl QueryEngine for DatabricksEngine { |
| 156 | async fn test(&self) -> anyhow::Result<()> { |
| 157 | self.run("SELECT 1").await.map(|_| ()) |
| 158 | } |
| 159 | |
| 160 | async fn fetch_schema(&self) -> anyhow::Result<Vec<SchemaColumn>> { |
| 161 | // 带 catalog 就查那个 catalog 的 information_schema;不带就是会话默认的 |
| 162 | let prefix = self |
| 163 | .conn |
| 164 | .catalog |
| 165 | .as_deref() |
| 166 | .map(|c| format!("`{}`.", c.replace('`', "``"))) |
| 167 | .unwrap_or_default(); |
| 168 | let schema_filter = self |
| 169 | .conn |
| 170 | .schema |
| 171 | .as_deref() |
| 172 | .map(|s| format!(" AND table_schema = {}", sql_literal(s))) |
| 173 | .unwrap_or_default(); |
| 174 | let sql = format!( |
| 175 | "SELECT table_schema, table_name, column_name, data_type, comment \ |
| 176 | FROM {prefix}information_schema.columns \ |
| 177 | WHERE table_schema <> 'information_schema'{schema_filter} \ |
| 178 | ORDER BY table_schema, table_name, ordinal_position" |
| 179 | ); |
| 180 | let (_, rows) = self.run(&sql).await?; |
| 181 | Ok(rows.into_iter().map(super::trino::schema_row).collect()) |
| 182 | } |
| 183 | |
| 184 | async fn execute(&self, sql: &str) -> anyhow::Result<QueryResult> { |
| 185 | let (columns, rows) = self.run(&wrap_limit(sql)).await?; |
| 186 | let (rows, truncated) = truncate_rows(rows); |
| 187 | Ok(QueryResult { |
| 188 | rows: rows_to_json_lines(&columns, &rows), |
| 189 | truncated, |
| 190 | }) |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | #[cfg(test)] |
| 195 | mod tests { |
| 196 | use super::super::conn::DatabricksConn; |
| 197 | use super::super::QueryEngine; |
| 198 | use super::DatabricksEngine; |
| 199 | use serde_json::json; |
| 200 | use wiremock::matchers::{header, method, path}; |
| 201 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 202 | |
| 203 | fn conn(server: &MockServer) -> DatabricksConn { |
| 204 | DatabricksConn::parse(&format!( |
| 205 | "databricks://:dapi-test@{}/sql/1.0/warehouses/wh1?catalog=main&ssl=false", |
| 206 | server.uri().trim_start_matches("http://") |
| 207 | )) |
| 208 | .unwrap() |
| 209 | } |
| 210 | |
| 211 | #[tokio::test] |
| 212 | async fn polls_until_succeeded_and_restores_types() { |
| 213 | let server = MockServer::start().await; |
| 214 | Mock::given(method("POST")) |
| 215 | .and(path("/api/2.0/sql/statements")) |
| 216 | .and(header("authorization", "Bearer dapi-test")) |
| 217 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 218 | "statement_id": "s1", |
| 219 | "status": { "state": "PENDING" } |
| 220 | }))) |
| 221 | .expect(1) |
| 222 | .mount(&server) |
| 223 | .await; |
| 224 | Mock::given(method("GET")) |
| 225 | .and(path("/api/2.0/sql/statements/s1")) |
| 226 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 227 | "statement_id": "s1", |
| 228 | "status": { "state": "SUCCEEDED" }, |
| 229 | "manifest": { "schema": { "columns": [ |
| 230 | { "name": "region", "type_text": "STRING", "position": 0 }, |
| 231 | { "name": "total", "type_text": "DECIMAL(12,2)", "position": 1 }, |
| 232 | { "name": "active", "type_text": "BOOLEAN", "position": 2 } |
| 233 | ] } }, |
| 234 | "result": { "data_array": [ ["east", "12.50", "true"], ["west", null, "false"] ] } |
| 235 | }))) |
| 236 | .expect(1) |
| 237 | .mount(&server) |
| 238 | .await; |
| 239 | |
| 240 | let out = DatabricksEngine::new(conn(&server)) |
| 241 | .execute("SELECT region, total, active FROM orders") |
| 242 | .await |
| 243 | .unwrap(); |
| 244 | assert_eq!( |
| 245 | out.rows, |
| 246 | vec![ |
| 247 | r#"{"region":"east","total":12.5,"active":true}"#, |
| 248 | r#"{"region":"west","total":null,"active":false}"# |
| 249 | ] |
| 250 | ); |
| 251 | } |
| 252 | |
| 253 | #[tokio::test] |
| 254 | async fn a_failed_statement_reports_the_message() { |
| 255 | let server = MockServer::start().await; |
| 256 | Mock::given(method("POST")) |
| 257 | .and(path("/api/2.0/sql/statements")) |
| 258 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 259 | "statement_id": "s2", |
| 260 | "status": { "state": "FAILED", "error": { "error_code": "BAD_REQUEST", "message": "TABLE_OR_VIEW_NOT_FOUND: nope" } } |
| 261 | }))) |
| 262 | .mount(&server) |
| 263 | .await; |
| 264 | let err = DatabricksEngine::new(conn(&server)) |
| 265 | .execute("SELECT * FROM nope") |
| 266 | .await |
| 267 | .unwrap_err() |
| 268 | .to_string(); |
| 269 | assert!(err.contains("TABLE_OR_VIEW_NOT_FOUND"), "{err}"); |
| 270 | } |
| 271 | } |