1use crate::{FlightData, SchemaAsIpc};
8use std::collections::HashMap;
9use std::sync::Arc;
10
11use arrow_array::{ArrayRef, RecordBatch};
12use arrow_buffer::Buffer;
13use arrow_ipc::convert::try_fb_to_schema;
14use arrow_ipc::writer::IpcWriteContext;
15use arrow_ipc::{reader, root_as_message, writer, writer::IpcWriteOptions};
16use arrow_schema::{ArrowError, Schema, SchemaRef};
17
18pub fn flight_data_to_batches(flight_data: &[FlightData]) -> Result<Vec<RecordBatch>, ArrowError> {
20 let schema = flight_data.first().ok_or_else(|| {
21 ArrowError::CastError("Need at least one FlightData for schema".to_string())
22 })?;
23 let message = root_as_message(&schema.data_header[..])
24 .map_err(|_| ArrowError::CastError("Cannot get root as message".to_string()))?;
25
26 let ipc_schema: arrow_ipc::Schema = message
27 .header_as_schema()
28 .ok_or_else(|| ArrowError::CastError("Cannot get header as Schema".to_string()))?;
29 let schema = try_fb_to_schema(ipc_schema)?;
30 let schema = Arc::new(schema);
31
32 let mut batches = vec![];
33 let dictionaries_by_id = HashMap::new();
34 for datum in &flight_data[1..] {
35 let batch = flight_data_to_arrow_batch(datum, schema.clone(), &dictionaries_by_id)?;
36 batches.push(batch);
37 }
38 Ok(batches)
39}
40
41pub fn flight_data_to_arrow_batch(
43 data: &FlightData,
44 schema: SchemaRef,
45 dictionaries_by_id: &HashMap<i64, ArrayRef>,
46) -> Result<RecordBatch, ArrowError> {
47 let message = arrow_ipc::root_as_message(&data.data_header[..])
49 .map_err(|err| ArrowError::ParseError(format!("Unable to get root as message: {err:?}")))?;
50
51 message
52 .header_as_record_batch()
53 .ok_or_else(|| {
54 ArrowError::ParseError(
55 "Unable to convert flight data header to a record batch".to_string(),
56 )
57 })
58 .map(|batch| {
59 reader::read_record_batch(
60 &Buffer::from(data.data_body.as_ref()),
61 batch,
62 schema,
63 dictionaries_by_id,
64 None,
65 &message.version(),
66 )
67 })?
68}
69
70pub fn batches_to_flight_data<'a>(
72 schema: &Schema,
73 batches: impl IntoIterator<Item = &'a RecordBatch>,
74) -> Result<Vec<FlightData>, ArrowError> {
75 let options = IpcWriteOptions::default();
76 let schema_flight_data: FlightData = SchemaAsIpc::new(schema, &options).into();
77 let mut dictionaries = vec![];
78 let mut flight_data = vec![];
79
80 let data_gen = writer::IpcDataGenerator::default();
81 let mut dictionary_tracker = writer::DictionaryTracker::new(false);
82 let mut ipc_write_context = IpcWriteContext::default();
83
84 for batch in batches {
85 let (encoded_dictionaries, encoded_batch) = data_gen.encode(
86 batch,
87 &mut dictionary_tracker,
88 &options,
89 &mut ipc_write_context,
90 )?;
91
92 dictionaries.extend(encoded_dictionaries.into_iter().map(Into::into));
93 flight_data.push(encoded_batch.into());
94 }
95
96 let mut stream = Vec::with_capacity(1 + dictionaries.len() + flight_data.len());
97
98 stream.push(schema_flight_data);
99 stream.extend(dictionaries);
100 stream.extend(flight_data);
101 let flight_data = stream;
102 Ok(flight_data)
103}