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}
48#[cfg(not(tarpaulin_include))]
53fn catch_df_schema_error(e: &ArrowError) -> Schema {
54 error!(
55 "Unable to convert from FFI_ArrowSchema to DataFusion Schema in FFI_PlanProperties. {e}"
56 );
57 Schema::empty()
58}
59
60impl From<WrappedSchema> for SchemaRef {
61 fn from(value: WrappedSchema) -> Self {
62 let schema =
63 Schema::try_from(&value.0).unwrap_or_else(|e| catch_df_schema_error(&e));
64 Arc::new(schema)
65 }
66}
67
68#[repr(C)]
72#[derive(Debug)]
73pub struct WrappedArray {
74 pub array: FFI_ArrowArray,
75 pub schema: WrappedSchema,
76}
77
78impl TryFrom<WrappedArray> for ArrayRef {
79 type Error = ArrowError;
80
81 fn try_from(value: WrappedArray) -> Result<Self, Self::Error> {
82 let data = unsafe { from_ffi(value.array, &value.schema.0)? };
83
84 Ok(make_array(data))
85 }
86}
87
88impl TryFrom<&ArrayRef> for WrappedArray {
89 type Error = ArrowError;
90
91 fn try_from(array: &ArrayRef) -> Result<Self, Self::Error> {
92 let (array, schema) = to_ffi(&array.to_data())?;
93 let schema = WrappedSchema(schema);
94
95 Ok(WrappedArray { array, schema })
96 }
97}
98
99impl TryFrom<&ScalarValue> for WrappedArray {
100 type Error = DataFusionError;
101
102 fn try_from(value: &ScalarValue) -> Result<Self, Self::Error> {
103 let array = value.to_array()?;
104 WrappedArray::try_from(&array).map_err(Into::into)
105 }
106}
107
108impl TryFrom<WrappedArray> for ScalarValue {
109 type Error = DataFusionError;
110
111 fn try_from(value: WrappedArray) -> Result<Self, Self::Error> {
112 let array: ArrayRef = value.try_into()?;
113 ScalarValue::try_from_array(array.as_ref(), 0)
114 }
115}