-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.rs
More file actions
424 lines (399 loc) · 14.1 KB
/
Copy pathquery.rs
File metadata and controls
424 lines (399 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use crate::sdk::Api;
use serde::Deserialize;
use serde_json::Value;
const ACCEPT_ARROW: &str = "application/vnd.apache.arrow.stream";
#[derive(Deserialize)]
pub struct QueryResponse {
pub result_id: Option<String>,
pub columns: Vec<String>,
pub rows: Vec<Vec<Value>>,
pub row_count: u64,
pub execution_time_ms: Option<u64>,
pub warning: Option<String>,
}
/// Convert the SDK's inline `QueryResponse` (200 path) into the CLI's display
/// model. The async path decodes Arrow instead (see `fetch_arrow_result`).
fn query_response_from_sdk(resp: hotdata::models::QueryResponse) -> QueryResponse {
QueryResponse {
result_id: resp.result_id.flatten(),
columns: resp.columns,
rows: resp.rows,
row_count: resp.row_count.max(0) as u64,
execution_time_ms: Some(resp.execution_time_ms.max(0) as u64),
warning: resp.warning.flatten(),
}
}
fn value_to_string(v: &Value) -> String {
match v {
Value::Null => "NULL".to_string(),
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.to_string(),
Value::String(s) => s.clone(),
Value::Array(arr) => {
let (formatted, count) = crate::table::truncate_array(arr);
match count {
Some(n) => format!("{formatted} ({n} items)"),
None => formatted,
}
}
Value::Object(_) => v.to_string(),
}
}
/// Convert one cell of an Arrow array to a `serde_json::Value`.
fn arrow_cell(col: &dyn arrow::array::Array, row: usize) -> Value {
use arrow::array::*;
use arrow::datatypes::DataType::*;
use serde_json::Number;
if col.is_null(row) {
return Value::Null;
}
match col.data_type() {
Boolean => Value::Bool(
col.as_any()
.downcast_ref::<BooleanArray>()
.unwrap()
.value(row),
),
Int8 => Value::Number(
col.as_any()
.downcast_ref::<Int8Array>()
.unwrap()
.value(row)
.into(),
),
Int16 => Value::Number(
col.as_any()
.downcast_ref::<Int16Array>()
.unwrap()
.value(row)
.into(),
),
Int32 => Value::Number(
col.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.value(row)
.into(),
),
Int64 => Value::Number(
col.as_any()
.downcast_ref::<Int64Array>()
.unwrap()
.value(row)
.into(),
),
UInt8 => Value::Number(
col.as_any()
.downcast_ref::<UInt8Array>()
.unwrap()
.value(row)
.into(),
),
UInt16 => Value::Number(
col.as_any()
.downcast_ref::<UInt16Array>()
.unwrap()
.value(row)
.into(),
),
UInt32 => Value::Number(
col.as_any()
.downcast_ref::<UInt32Array>()
.unwrap()
.value(row)
.into(),
),
UInt64 => Value::Number(
col.as_any()
.downcast_ref::<UInt64Array>()
.unwrap()
.value(row)
.into(),
),
Float32 => {
let v = col
.as_any()
.downcast_ref::<Float32Array>()
.unwrap()
.value(row) as f64;
Number::from_f64(v)
.map(Value::Number)
.unwrap_or(Value::Null)
}
Float64 => {
let v = col
.as_any()
.downcast_ref::<Float64Array>()
.unwrap()
.value(row);
Number::from_f64(v)
.map(Value::Number)
.unwrap_or(Value::Null)
}
Utf8 => Value::String(
col.as_any()
.downcast_ref::<StringArray>()
.unwrap()
.value(row)
.to_owned(),
),
LargeUtf8 => Value::String(
col.as_any()
.downcast_ref::<LargeStringArray>()
.unwrap()
.value(row)
.to_owned(),
),
// Dates, timestamps, decimals, etc. — format via Arrow's display helper.
_ => {
use arrow::util::display::{ArrayFormatter, FormatOptions};
let opts = FormatOptions::default();
ArrayFormatter::try_new(col, &opts)
.map(|f| Value::String(f.value(row).to_string()))
.unwrap_or(Value::Null)
}
}
}
/// Decode an Arrow IPC stream into a `QueryResponse` suitable for display.
fn arrow_ipc_to_query_response(bytes: Vec<u8>, result_id: String) -> QueryResponse {
use arrow::ipc::reader::StreamReader;
use std::io::Cursor;
let reader = match StreamReader::try_new(Cursor::new(&bytes), None) {
Ok(r) => r,
Err(e) => {
eprintln!("error reading Arrow IPC stream: {e}");
std::process::exit(1);
}
};
let columns: Vec<String> = reader
.schema()
.fields()
.iter()
.map(|f| f.name().clone())
.collect();
let mut rows: Vec<Vec<Value>> = Vec::new();
for batch_result in reader {
let batch = match batch_result {
Ok(b) => b,
Err(e) => {
eprintln!("error reading Arrow batch: {e}");
std::process::exit(1);
}
};
for row in 0..batch.num_rows() {
rows.push(
(0..batch.num_columns())
.map(|c| arrow_cell(batch.column(c).as_ref(), row))
.collect(),
);
}
}
let row_count = rows.len() as u64;
QueryResponse {
result_id: Some(result_id),
columns,
rows,
row_count,
execution_time_ms: None,
warning: None,
}
}
/// Fetch `/results/{result_id}` as Arrow IPC and return a `QueryResponse`.
///
/// The Arrow stream is fetched through the SDK seam ([`Api::get_bytes`]) — same
/// auth/transport as every other call — but decoded here with the CLI's own
/// pinned `arrow` crate rather than the SDK's `get_result_arrow` (whose
/// `RecordBatch` comes from a different `arrow` major version).
pub(crate) fn fetch_arrow_result(api: &Api, result_id: &str) -> QueryResponse {
let (status, bytes) = api
.get_bytes(&format!("/results/{result_id}"), ACCEPT_ARROW)
.unwrap_or_else(|e| e.exit());
if !status.is_success() {
use crossterm::style::Stylize;
let msg = String::from_utf8_lossy(&bytes);
eprintln!("{}", format!("error fetching result: {status} {msg}").red());
std::process::exit(1);
}
arrow_ipc_to_query_response(bytes, result_id.to_owned())
}
pub fn execute(sql: &str, workspace_id: &str, database: Option<&str>, format: &str) {
let api = Api::new(Some(workspace_id));
// Scope to the explicit --database flag, else the active database resolved
// at construction (HOTDATA_DATABASE / current database). submit_query sends
// it as the X-Database-Id header.
let database = database.or(api.database_id());
let mut request = hotdata::models::QueryRequest::new(sql.to_string());
request.r#async = Some(true);
request.async_after_ms = Some(Some(1000));
let spinner = crate::util::spinner("running query...");
let outcome = crate::sdk::block(api.client().submit_query(request, database))
.unwrap_or_else(|e| e.exit());
spinner.finish_and_clear();
let async_resp = match outcome {
// Completed within async_after_ms — inline results.
hotdata::QueryOutcome::Inline(resp) => {
print_result(&query_response_from_sdk(resp), format);
return;
}
// Still running — poll the query run, then fetch the result as Arrow.
hotdata::QueryOutcome::Submitted(async_resp) => async_resp,
// QueryOutcome is #[non_exhaustive]; guard against future variants.
_ => {
eprintln!("unexpected query response from server");
std::process::exit(1);
}
};
let run_id = &async_resp.query_run_id;
let spinner = crate::util::spinner("waiting for query...");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
loop {
// Drive the poll loop ourselves to preserve the 5-minute deadline and
// 500ms cadence (NOT the SDK's PollConfig defaults).
let run =
crate::sdk::block(api.client().query_runs().get(run_id)).unwrap_or_else(|e| e.exit());
match run.status.as_str() {
"succeeded" => {
spinner.finish_and_clear();
match run.result_id.flatten() {
Some(ref result_id) => {
let result = fetch_arrow_result(&api, result_id);
print_result(&result, format);
}
None => {
use crossterm::style::Stylize;
println!("{}", "Query succeeded but no result available.".yellow());
}
}
return;
}
"failed" => {
spinner.finish_and_clear();
use crossterm::style::Stylize;
let err = run
.error_message
.flatten()
.unwrap_or_else(|| "unknown error".to_string());
eprintln!("{}", format!("query failed: {err}").red());
std::process::exit(1);
}
"running" | "queued" | "pending" => {}
status => {
spinner.finish_and_clear();
use crossterm::style::Stylize;
eprintln!("{}", format!("query status: {status}").yellow());
eprintln!(
"{}",
format!("Check status with: hotdata query status {run_id}").dark_grey()
);
std::process::exit(2);
}
}
if std::time::Instant::now() > deadline {
spinner.finish_and_clear();
use crossterm::style::Stylize;
eprintln!("{}", "query timed out after 5 minutes".red());
eprintln!(
"{}",
format!("Check status with: hotdata query status {run_id}").dark_grey()
);
std::process::exit(1);
}
std::thread::sleep(std::time::Duration::from_millis(500));
}
}
/// Poll a query run by ID. If succeeded and has a result_id, fetch and display the result.
pub fn poll(query_run_id: &str, workspace_id: &str, format: &str) {
let api = Api::new(Some(workspace_id));
let run =
crate::sdk::block(api.client().query_runs().get(query_run_id)).unwrap_or_else(|e| e.exit());
match run.status.as_str() {
"succeeded" => match run.result_id.flatten() {
Some(ref result_id) => {
let result = fetch_arrow_result(&api, result_id);
print_result(&result, format);
}
None => {
use crossterm::style::Stylize;
println!("{}", "Query succeeded but no result available.".yellow());
}
},
"failed" => {
use crossterm::style::Stylize;
let err = run
.error_message
.flatten()
.unwrap_or_else(|| "unknown error".to_string());
eprintln!("{}", format!("query failed: {err}").red());
std::process::exit(1);
}
status => {
use crossterm::style::Stylize;
eprintln!("{}", format!("query status: {status}").yellow());
eprintln!("query_run_id: {}", run.id);
eprintln!(
"{}",
format!("Poll again with: hotdata query status {}", run.id).dark_grey()
);
std::process::exit(2);
}
}
}
pub fn print_result(result: &QueryResponse, format: &str) {
if let Some(ref warning) = result.warning {
eprintln!("warning: {warning}");
}
match format {
"json" => {
let out = serde_json::json!({
"result_id": result.result_id,
"columns": result.columns,
"rows": result.rows,
"row_count": result.row_count,
"execution_time_ms": result.execution_time_ms,
});
println!("{}", serde_json::to_string_pretty(&out).unwrap());
}
"csv" => {
println!("{}", result.columns.join(","));
for row in &result.rows {
let cells: Vec<String> = row
.iter()
.map(|v| {
let s = value_to_string(v);
if s.contains(',') || s.contains('"') || s.contains('\n') {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s
}
})
.collect();
println!("{}", cells.join(","));
}
}
"table" => {
crate::table::print_json(&result.columns, &result.rows);
use crossterm::style::Stylize;
let id_part = result
.result_id
.as_deref()
.map(|id| format!(" [result-id: {id}]"))
.unwrap_or_default();
let time_part = match result.execution_time_ms {
Some(ms) => format!("{ms} ms"),
None => "\u{2014}".to_string(), // em dash
};
eprintln!(
"{}",
format!(
"\n{} row{} ({}){}",
result.row_count,
if result.row_count == 1 { "" } else { "s" },
time_part,
id_part
)
.dark_grey()
);
}
_ => unreachable!(),
}
}