|
17 | 17 | */ |
18 | 18 |
|
19 | 19 | use actix_web::http::StatusCode; |
20 | | -use actix_web::{HttpResponse, HttpResponseBuilder}; |
21 | | -use datafusion::arrow::json; |
| 20 | +use actix_web::{web, Responder}; |
| 21 | +use datafusion::arrow::json::writer::record_batches_to_json_rows; |
22 | 22 | use datafusion::arrow::record_batch::RecordBatch; |
| 23 | +use itertools::Itertools; |
| 24 | +use serde_json::Value; |
23 | 25 |
|
24 | 26 | pub struct QueryResponse { |
25 | 27 | pub code: StatusCode, |
26 | | - pub body: Vec<RecordBatch>, |
| 28 | + pub records: Vec<RecordBatch>, |
| 29 | + pub fields: Vec<String>, |
| 30 | + pub fill_null: bool, |
27 | 31 | } |
28 | 32 |
|
29 | 33 | impl QueryResponse { |
30 | | - pub fn to_http(&self) -> HttpResponse { |
31 | | - log::info!("{}", "Returning query results"); |
32 | | - let buf = Vec::new(); |
33 | | - let mut writer = json::ArrayWriter::new(buf); |
34 | | - writer.write_batches(&self.body).unwrap(); |
35 | | - writer.finish().unwrap(); |
36 | | - |
37 | | - HttpResponseBuilder::new(self.code) |
38 | | - .content_type("json") |
39 | | - .body(writer.into_inner()) |
40 | | - } |
41 | | -} |
42 | | - |
43 | | -impl From<Vec<RecordBatch>> for QueryResponse { |
44 | | - fn from(body: Vec<RecordBatch>) -> Self { |
| 34 | + pub fn new(records: Vec<RecordBatch>, fields: Vec<String>, fill_null: bool) -> Self { |
45 | 35 | Self { |
46 | 36 | code: StatusCode::OK, |
47 | | - body, |
| 37 | + records, |
| 38 | + fields, |
| 39 | + fill_null, |
48 | 40 | } |
49 | 41 | } |
| 42 | + |
| 43 | + pub fn to_http(&self) -> impl Responder { |
| 44 | + log::info!("{}", "Returning query results"); |
| 45 | + let mut json_records = record_batches_to_json_rows(&self.records).unwrap(); |
| 46 | + |
| 47 | + if self.fill_null { |
| 48 | + for map in &mut json_records { |
| 49 | + for field in &self.fields { |
| 50 | + if !map.contains_key(field) { |
| 51 | + map.insert(field.clone(), Value::Null); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + let values = json_records.into_iter().map(Value::Object).collect_vec(); |
| 58 | + web::Json(values) |
| 59 | + } |
50 | 60 | } |
0 commit comments