datafusion_ffi/
arrow_wrappers.rs1use std::sync::Arc;
19
20use arrow::array::{ArrayRef, make_array};
21use arrow::datatypes::{Schema, SchemaRef};
22use arrow::error::ArrowError;
23use arrow::ffi::{FFI_ArrowArray, FFI_ArrowSchema, from_ffi, to_ffi};
24use datafusion_common::{DataFusionError, ScalarValue};
25use log::error;
26
27#[repr(C)]
30#[derive(Debug)]
31pub struct WrappedSchema(pub FFI_ArrowSchema);
32
33impl From<SchemaRef> for WrappedSchema {
34 fn from(value: SchemaRef) -> Self {
35 let ffi_schema = match FFI_ArrowSchema::try_from(value.as_ref()) {
36 Ok(s) => s,
37 Err(e) => {
38 error!(
39 "Unable to convert DataFusion Schema to FFI_ArrowSchema in FFI_PlanProperties. {e}"
40 );
41 FFI_ArrowSchema::empty()
42 }
43 };
44
45 WrappedSchema(ffi_schema)
46 }
47}
48fn catch_df_schema_error(e: &ArrowError) -> Schema {
53 error!(
54 "Unable to convert from FFI_ArrowSchema to DataFusion Schema in FFI_PlanProperties. {e}"
55 );
56 Schema::empty()
57}
58
59impl From<WrappedSchema> for SchemaRef {
60 fn from(value: WrappedSchema) -> Self {
61 let schema =
62 Schema::try_from(&value.0).unwrap_or_else(|e| catch_df_schema_error(&e));
63 Arc::new(schema)
64 }
65}
66
67#[repr(C)]
71#[derive(Debug)]
72pub struct WrappedArray {
73 pub array: FFI_ArrowArray,
74 pub schema: WrappedSchema,
75}
76
77impl TryFrom<WrappedArray> for ArrayRef {
78 type Error = ArrowError;
79
80 fn try_from(value: WrappedArray) -> Result<Self, Self::Error> {
81 let data = unsafe { from_ffi(value.array, &value.schema.0)? };
82
83 Ok(make_array(data))
84 }
85}
86
87impl TryFrom<&ArrayRef> for WrappedArray {
88 type Error = ArrowError;
89
90 fn try_from(array: &ArrayRef) -> Result<Self, Self::Error> {
91 let (array, schema) = to_ffi(&array.to_data())?;
92 let schema = WrappedSchema(schema);
93
94 Ok(WrappedArray { array, schema })
95 }
96}
97
98impl TryFrom<&ScalarValue> for WrappedArray {
99 type Error = DataFusionError;
100
101 fn try_from(value: &ScalarValue) -> Result<Self, Self::Error> {
102 let array = value.to_array()?;
103 WrappedArray::try_from(&array).map_err(Into::into)
104 }
105}
106
107impl TryFrom<WrappedArray> for ScalarValue {
108 type Error = DataFusionError;
109
110 fn try_from(value: WrappedArray) -> Result<Self, Self::Error> {
111 let array: ArrayRef = value.try_into()?;
112 ScalarValue::try_from_array(array.as_ref(), 0)
113 }
114}