| 1 | //! Snowflake SQL API v2(`/api/v2/statements`)。同步提交(`async=false`)拿不完的 |
| 2 | //! 语句回 202,沿 statementHandle 轮询。值全是字符串,按 rowType 还原数与布尔。 |
| 3 | //! |
| 4 | //! 只收令牌,不收密码:programmatic access token 或 OAuth。密钥对 JWT 要本地签名, |
| 5 | //! 这一版不做——见 `conn.rs`。 |
| 6 | |
| 7 | use super::conn::SnowflakeConn; |
| 8 | use super::{ |
| 9 | coerce, rows_to_json_lines, sql_literal, truncate_rows, wrap_limit, QueryEngine, QueryResult, |
| 10 | SchemaColumn, HTTP_POLL_BUDGET, STATEMENT_TIMEOUT_SECS, |
| 11 | }; |
| 12 | use reqwest::StatusCode; |
| 13 | use serde::Deserialize; |
| 14 | use serde_json::json; |
| 15 | use std::time::{Duration, Instant}; |
| 16 | |
| 17 | pub struct SnowflakeEngine { |
| 18 | conn: SnowflakeConn, |
| 19 | } |
| 20 | |
| 21 | #[derive(Deserialize)] |
| 22 | struct StatementResponse { |
| 23 | #[serde(rename = "resultSetMetaData")] |
| 24 | meta: Option<Meta>, |
| 25 | data: Option<Vec<Vec<serde_json::Value>>>, |
| 26 | message: Option<String>, |
| 27 | code: Option<String>, |
| 28 | #[serde(rename = "statementHandle")] |
| 29 | handle: Option<String>, |
| 30 | } |
| 31 | |
| 32 | #[derive(Deserialize)] |
| 33 | struct Meta { |
| 34 | #[serde(rename = "rowType")] |
| 35 | row_type: Vec<RowType>, |
| 36 | } |
| 37 | |
| 38 | #[derive(Deserialize)] |
| 39 | struct RowType { |
| 40 | name: String, |
| 41 | #[serde(rename = "type")] |
| 42 | ty: String, |
| 43 | } |
| 44 | |
| 45 | impl SnowflakeEngine { |
| 46 | pub fn new(conn: SnowflakeConn) -> Self { |
| 47 | Self { conn } |
| 48 | } |
| 49 | |
| 50 | fn request(&self, r: reqwest::RequestBuilder) -> reqwest::RequestBuilder { |
| 51 | r.bearer_auth(&self.conn.token) |
| 52 | .header("X-Snowflake-Authorization-Token-Type", self.conn.token_type) |
| 53 | .header("Accept", "application/json") |
| 54 | } |
| 55 | |
| 56 | async fn run(&self, sql: &str) -> anyhow::Result<(Vec<String>, Vec<Vec<serde_json::Value>>)> { |
| 57 | let client = super::http()?; |
| 58 | let mut body = json!({ |
| 59 | "statement": sql, |
| 60 | "timeout": STATEMENT_TIMEOUT_SECS, |
| 61 | "parameters": { "MULTI_STATEMENT_COUNT": "1" }, |
| 62 | }); |
| 63 | for (key, value) in [ |
| 64 | ("database", &self.conn.database), |
| 65 | ("schema", &self.conn.schema), |
| 66 | ("warehouse", &self.conn.warehouse), |
| 67 | ("role", &self.conn.role), |
| 68 | ] { |
| 69 | if let Some(v) = value { |
| 70 | body[key] = json!(v); |
| 71 | } |
| 72 | } |
| 73 | let mut http = self |
| 74 | .request(client.post(format!("{}/api/v2/statements?async=false", self.conn.base))) |
| 75 | .json(&body) |
| 76 | .send() |
| 77 | .await?; |
| 78 | let started = Instant::now(); |
| 79 | // 202 = 还在跑;其余非 2xx 的 body 里带 message |
| 80 | while http.status() == StatusCode::ACCEPTED { |
| 81 | let partial: StatementResponse = http.json().await?; |
| 82 | let handle = partial.handle.ok_or_else(|| { |
| 83 | anyhow::anyhow!("Snowflake returned 202 without a statementHandle") |
| 84 | })?; |
| 85 | if started.elapsed() > HTTP_POLL_BUDGET { |
| 86 | anyhow::bail!( |
| 87 | "Snowflake statement did not finish within {}s", |
| 88 | HTTP_POLL_BUDGET.as_secs() |
| 89 | ); |
| 90 | } |
| 91 | tokio::time::sleep(Duration::from_secs(1)).await; |
| 92 | http = self |
| 93 | .request(client.get(format!("{}/api/v2/statements/{handle}", self.conn.base))) |
| 94 | .send() |
| 95 | .await?; |
| 96 | } |
| 97 | if !http.status().is_success() { |
| 98 | let status = http.status(); |
| 99 | let text = http.text().await.unwrap_or_default(); |
| 100 | let msg = serde_json::from_str::<StatementResponse>(&text) |
| 101 | .ok() |
| 102 | .and_then(|r| r.message) |
| 103 | .unwrap_or(text); |
| 104 | anyhow::bail!("Snowflake {status}: {msg}"); |
| 105 | } |
| 106 | let resp: StatementResponse = http.json().await?; |
| 107 | if let (Some(code), Some(message)) = (&resp.code, &resp.message) { |
| 108 | // 2xx 里也可能带业务错误码;090001 是 "statement executed successfully" |
| 109 | if code != "090001" && resp.meta.is_none() { |
| 110 | anyhow::bail!("Snowflake {code}: {message}"); |
| 111 | } |
| 112 | } |
| 113 | let types: Vec<RowType> = resp.meta.map(|m| m.row_type).unwrap_or_default(); |
| 114 | let rows = resp |
| 115 | .data |
| 116 | .unwrap_or_default() |
| 117 | .into_iter() |
| 118 | .map(|row| { |
| 119 | row.iter() |
| 120 | .enumerate() |
| 121 | .map(|(i, v)| coerce(types.get(i).map(|t| t.ty.as_str()).unwrap_or(""), v)) |
| 122 | .collect() |
| 123 | }) |
| 124 | .collect(); |
| 125 | Ok((types.into_iter().map(|t| t.name).collect(), rows)) |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | #[async_trait::async_trait] |
| 130 | impl QueryEngine for SnowflakeEngine { |
| 131 | async fn test(&self) -> anyhow::Result<()> { |
| 132 | self.run("SELECT 1").await.map(|_| ()) |
| 133 | } |
| 134 | |
| 135 | async fn fetch_schema(&self) -> anyhow::Result<Vec<SchemaColumn>> { |
| 136 | let database = self.conn.database.as_deref().ok_or_else(|| { |
| 137 | anyhow::anyhow!("snowflake://: put the database in the connection string (snowflake://:TOKEN@account/DATABASE) so the schema can be read") |
| 138 | })?; |
| 139 | let schema_filter = self |
| 140 | .conn |
| 141 | .schema |
| 142 | .as_deref() |
| 143 | .map(|s| format!(" AND table_schema = {}", sql_literal(s))) |
| 144 | .unwrap_or_default(); |
| 145 | let sql = format!( |
| 146 | "SELECT table_schema, table_name, column_name, data_type, comment \ |
| 147 | FROM \"{}\".information_schema.columns \ |
| 148 | WHERE table_schema <> 'INFORMATION_SCHEMA'{schema_filter} \ |
| 149 | ORDER BY table_schema, table_name, ordinal_position", |
| 150 | database.replace('"', "\"\"") |
| 151 | ); |
| 152 | let (_, rows) = self.run(&sql).await?; |
| 153 | Ok(rows.into_iter().map(super::trino::schema_row).collect()) |
| 154 | } |
| 155 | |
| 156 | async fn execute(&self, sql: &str) -> anyhow::Result<QueryResult> { |
| 157 | let (columns, rows) = self.run(&wrap_limit(sql)).await?; |
| 158 | let (rows, truncated) = truncate_rows(rows); |
| 159 | Ok(QueryResult { |
| 160 | rows: rows_to_json_lines(&columns, &rows), |
| 161 | truncated, |
| 162 | }) |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | #[cfg(test)] |
| 167 | mod tests { |
| 168 | use super::super::conn::SnowflakeConn; |
| 169 | use super::super::QueryEngine; |
| 170 | use super::SnowflakeEngine; |
| 171 | use serde_json::json; |
| 172 | use wiremock::matchers::{header, method, path}; |
| 173 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 174 | |
| 175 | fn conn(server: &MockServer) -> SnowflakeConn { |
| 176 | SnowflakeConn::parse(&format!( |
| 177 | "snowflake://:pat-test@{}/ANALYTICS/PUBLIC?warehouse=WH&ssl=false", |
| 178 | server.uri().trim_start_matches("http://") |
| 179 | )) |
| 180 | .unwrap() |
| 181 | } |
| 182 | |
| 183 | #[tokio::test] |
| 184 | async fn a_synchronous_answer_is_typed_by_row_type() { |
| 185 | let server = MockServer::start().await; |
| 186 | Mock::given(method("POST")) |
| 187 | .and(path("/api/v2/statements")) |
| 188 | .and(header("authorization", "Bearer pat-test")) |
| 189 | .and(header( |
| 190 | "X-Snowflake-Authorization-Token-Type", |
| 191 | "PROGRAMMATIC_ACCESS_TOKEN", |
| 192 | )) |
| 193 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 194 | "resultSetMetaData": { "numRows": 1, "rowType": [ |
| 195 | { "name": "REGION", "type": "text" }, |
| 196 | { "name": "TOTAL", "type": "fixed", "scale": 2 } |
| 197 | ] }, |
| 198 | "data": [ ["east", "42.10"] ], |
| 199 | "code": "090001", |
| 200 | "statementHandle": "h1", |
| 201 | "message": "Statement executed successfully." |
| 202 | }))) |
| 203 | .expect(1) |
| 204 | .mount(&server) |
| 205 | .await; |
| 206 | let out = SnowflakeEngine::new(conn(&server)) |
| 207 | .execute("SELECT region, total FROM orders") |
| 208 | .await |
| 209 | .unwrap(); |
| 210 | assert_eq!(out.rows, vec![r#"{"REGION":"east","TOTAL":42.1}"#]); |
| 211 | } |
| 212 | |
| 213 | #[tokio::test] |
| 214 | async fn a_202_is_polled_until_the_answer_arrives() { |
| 215 | let server = MockServer::start().await; |
| 216 | Mock::given(method("POST")) |
| 217 | .and(path("/api/v2/statements")) |
| 218 | .respond_with(ResponseTemplate::new(202).set_body_json(json!({ |
| 219 | "code": "333334", "statementHandle": "h2", "message": "Asynchronous execution in progress." |
| 220 | }))) |
| 221 | .expect(1) |
| 222 | .mount(&server) |
| 223 | .await; |
| 224 | Mock::given(method("GET")) |
| 225 | .and(path("/api/v2/statements/h2")) |
| 226 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 227 | "resultSetMetaData": { "rowType": [ { "name": "N", "type": "fixed" } ] }, |
| 228 | "data": [ ["1"] ], "code": "090001", "statementHandle": "h2" |
| 229 | }))) |
| 230 | .expect(1) |
| 231 | .mount(&server) |
| 232 | .await; |
| 233 | let out = SnowflakeEngine::new(conn(&server)) |
| 234 | .execute("SELECT 1 AS n") |
| 235 | .await |
| 236 | .unwrap(); |
| 237 | assert_eq!(out.rows, vec![r#"{"N":1}"#]); |
| 238 | } |
| 239 | |
| 240 | #[tokio::test] |
| 241 | async fn an_error_body_is_surfaced() { |
| 242 | let server = MockServer::start().await; |
| 243 | Mock::given(method("POST")) |
| 244 | .and(path("/api/v2/statements")) |
| 245 | .respond_with(ResponseTemplate::new(422).set_body_json(json!({ |
| 246 | "code": "002003", "message": "SQL compilation error: Object 'NOPE' does not exist" |
| 247 | }))) |
| 248 | .mount(&server) |
| 249 | .await; |
| 250 | let err = SnowflakeEngine::new(conn(&server)) |
| 251 | .execute("SELECT * FROM nope") |
| 252 | .await |
| 253 | .unwrap_err() |
| 254 | .to_string(); |
| 255 | assert!(err.contains("does not exist"), "{err}"); |
| 256 | } |
| 257 | } |