1use arrow_array::Array as ArrowArray;
5use arrow_array::ArrayRef as ArrowArrayRef;
6use arrow_array::Datum as ArrowDatum;
7use arrow_schema::DataType;
8use arrow_schema::Field;
9use vortex_array::ArrayRef;
10use vortex_array::ExecutionCtx;
11use vortex_array::IntoArray;
12use vortex_array::arrays::Constant;
13use vortex_array::arrays::ConstantArray;
14use vortex_error::VortexResult;
15use vortex_error::vortex_panic;
16
17use crate::ArrowSessionExt;
18use crate::ExecuteArrowExt;
19
20#[derive(Debug)]
32pub struct Datum {
33 array: ArrowArrayRef,
34 is_scalar: bool,
35}
36
37impl Datum {
38 pub fn try_new(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
40 if array.is::<Constant>() {
41 Ok(Self {
42 array: array.slice(0..1)?.execute_arrow(None, ctx)?,
43 is_scalar: true,
44 })
45 } else {
46 Ok(Self {
47 array: array.clone().execute_arrow(None, ctx)?,
48 is_scalar: false,
49 })
50 }
51 }
52
53 pub fn try_new_array(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
56 Ok(Self {
57 array: array.clone().execute_arrow(None, ctx)?,
58 is_scalar: false,
59 })
60 }
61
62 pub fn try_new_with_target_datatype(
63 array: &ArrayRef,
64 target_datatype: &DataType,
65 ctx: &mut ExecutionCtx,
66 ) -> VortexResult<Self> {
67 let target_field = Field::new(
68 String::new(),
69 target_datatype.clone(),
70 array.dtype().is_nullable(),
71 );
72
73 if array.is::<Constant>() {
74 Ok(Self {
75 array: array.slice(0..1)?.execute_arrow(Some(&target_field), ctx)?,
76 is_scalar: true,
77 })
78 } else {
79 Ok(Self {
80 array: array.clone().execute_arrow(Some(&target_field), ctx)?,
81 is_scalar: false,
82 })
83 }
84 }
85
86 pub fn data_type(&self) -> &DataType {
87 self.array.data_type()
88 }
89}
90
91impl ArrowDatum for Datum {
92 fn get(&self) -> (&dyn ArrowArray, bool) {
93 (&self.array, self.is_scalar)
94 }
95}
96
97pub fn from_arrow_columnar(
110 array: ArrowArrayRef,
111 len: usize,
112 nullable: bool,
113 ctx: &mut ExecutionCtx,
114) -> VortexResult<ArrayRef> {
115 let session = ctx.session().clone();
116 let array = session.arrow().from_arrow_array(array, nullable)?;
117 if array.len() == len {
118 return Ok(array);
119 }
120
121 if array.len() != 1 {
122 vortex_panic!(
123 "Array length mismatch, expected {} got {} for encoding {}",
124 len,
125 array.len(),
126 array.encoding_id()
127 );
128 }
129
130 Ok(ConstantArray::new(array.execute_scalar(0, ctx)?, len).into_array())
131}