vortex_array/arrays/varbin/compute/
compare.rs1use arrow_array::BinaryArray;
5use arrow_array::StringArray;
6use arrow_ord::cmp;
7use vortex_buffer::BitBuffer;
8use vortex_error::VortexExpect as _;
9use vortex_error::VortexResult;
10use vortex_error::vortex_bail;
11use vortex_error::vortex_err;
12
13use crate::Array;
14use crate::ArrayRef;
15use crate::ExecutionCtx;
16use crate::IntoArray;
17use crate::arrays::BoolArray;
18use crate::arrays::PrimitiveArray;
19use crate::arrays::VarBinArray;
20use crate::arrays::VarBinVTable;
21use crate::arrays::VarBinViewArray;
22use crate::arrow::Datum;
23use crate::arrow::from_arrow_array_with_len;
24use crate::builtins::ArrayBuiltins;
25use crate::dtype::DType;
26use crate::dtype::IntegerPType;
27use crate::match_each_integer_ptype;
28use crate::scalar_fn::fns::binary::CompareKernel;
29use crate::scalar_fn::fns::operators::CompareOperator;
30use crate::scalar_fn::fns::operators::Operator;
31use crate::vtable::ValidityHelper;
32
33impl CompareKernel for VarBinVTable {
35 fn compare(
36 lhs: &VarBinArray,
37 rhs: &ArrayRef,
38 operator: CompareOperator,
39 ctx: &mut ExecutionCtx,
40 ) -> VortexResult<Option<ArrayRef>> {
41 if let Some(rhs_const) = rhs.as_constant() {
42 let nullable = lhs.dtype().is_nullable() || rhs_const.dtype().is_nullable();
43 let len = lhs.len();
44
45 let rhs_is_empty = match rhs_const.dtype() {
46 DType::Binary(_) => rhs_const
47 .as_binary()
48 .is_empty()
49 .vortex_expect("RHS should not be null"),
50 DType::Utf8(_) => rhs_const
51 .as_utf8()
52 .is_empty()
53 .vortex_expect("RHS should not be null"),
54 _ => vortex_bail!("VarBinArray can only have type of Binary or Utf8"),
55 };
56
57 if rhs_is_empty {
58 let buffer = match operator {
59 CompareOperator::Gte => BitBuffer::new_set(len), CompareOperator::Lt => BitBuffer::new_unset(len), CompareOperator::Eq | CompareOperator::Lte => {
62 let lhs_offsets = lhs.offsets().clone().execute::<PrimitiveArray>(ctx)?;
63 match_each_integer_ptype!(lhs_offsets.ptype(), |P| {
64 compare_offsets_to_empty::<P>(lhs_offsets, true)
65 })
66 }
67 CompareOperator::NotEq | CompareOperator::Gt => {
68 let lhs_offsets = lhs.offsets().clone().execute::<PrimitiveArray>(ctx)?;
69 match_each_integer_ptype!(lhs_offsets.ptype(), |P| {
70 compare_offsets_to_empty::<P>(lhs_offsets, false)
71 })
72 }
73 };
74
75 return Ok(Some(
76 BoolArray::new(
77 buffer,
78 lhs.validity()
79 .clone()
80 .union_nullability(rhs.dtype().nullability()),
81 )
82 .into_array(),
83 ));
84 }
85
86 let lhs = Datum::try_new(&lhs.to_array())?;
87
88 let arrow_rhs: &dyn arrow_array::Datum = match rhs_const.dtype() {
91 DType::Utf8(_) => &rhs_const
92 .as_utf8()
93 .value()
94 .map(StringArray::new_scalar)
95 .unwrap_or_else(|| arrow_array::Scalar::new(StringArray::new_null(1))),
96 DType::Binary(_) => &rhs_const
97 .as_binary()
98 .value()
99 .map(BinaryArray::new_scalar)
100 .unwrap_or_else(|| arrow_array::Scalar::new(BinaryArray::new_null(1))),
101 _ => vortex_bail!(
102 "VarBin array RHS can only be Utf8 or Binary, given {}",
103 rhs_const.dtype()
104 ),
105 };
106
107 let array = match operator {
108 CompareOperator::Eq => cmp::eq(&lhs, arrow_rhs),
109 CompareOperator::NotEq => cmp::neq(&lhs, arrow_rhs),
110 CompareOperator::Gt => cmp::gt(&lhs, arrow_rhs),
111 CompareOperator::Gte => cmp::gt_eq(&lhs, arrow_rhs),
112 CompareOperator::Lt => cmp::lt(&lhs, arrow_rhs),
113 CompareOperator::Lte => cmp::lt_eq(&lhs, arrow_rhs),
114 }
115 .map_err(|err| vortex_err!("Failed to compare VarBin array: {}", err))?;
116
117 Ok(Some(from_arrow_array_with_len(&array, len, nullable)?))
118 } else if !rhs.is::<VarBinVTable>() {
119 return Ok(Some(
123 lhs.to_array()
124 .execute::<VarBinViewArray>(ctx)?
125 .to_array()
126 .binary(rhs.to_array(), Operator::from(operator))?,
127 ));
128 } else {
129 Ok(None)
130 }
131 }
132}
133
134fn compare_offsets_to_empty<P: IntegerPType>(offsets: PrimitiveArray, eq: bool) -> BitBuffer {
135 let fn_ = if eq { P::eq } else { P::ne };
136 let offsets = offsets.as_slice::<P>();
137 BitBuffer::collect_bool(offsets.len() - 1, |idx| {
138 let left = unsafe { offsets.get_unchecked(idx) };
139 let right = unsafe { offsets.get_unchecked(idx + 1) };
140 fn_(left, right)
141 })
142}
143
144#[cfg(test)]
145mod test {
146 use vortex_buffer::BitBuffer;
147 use vortex_buffer::ByteBuffer;
148
149 use crate::ToCanonical;
150 use crate::arrays::ConstantArray;
151 use crate::arrays::VarBinArray;
152 use crate::arrays::VarBinViewArray;
153 use crate::builtins::ArrayBuiltins;
154 use crate::dtype::DType;
155 use crate::dtype::Nullability;
156 use crate::scalar::Scalar;
157 use crate::scalar_fn::fns::operators::Operator;
158
159 #[test]
160 fn test_binary_compare() {
161 let array = VarBinArray::from_iter(
162 [Some(b"abc".to_vec()), None, Some(b"def".to_vec())],
163 DType::Binary(Nullability::Nullable),
164 );
165 let result = array
166 .to_array()
167 .binary(
168 ConstantArray::new(
169 Scalar::binary(ByteBuffer::copy_from(b"abc"), Nullability::Nullable),
170 3,
171 )
172 .to_array(),
173 Operator::Eq,
174 )
175 .unwrap()
176 .to_bool();
177
178 assert_eq!(
179 &result.validity_mask().unwrap().to_bit_buffer(),
180 &BitBuffer::from_iter([true, false, true])
181 );
182 assert_eq!(
183 result.to_bit_buffer(),
184 BitBuffer::from_iter([true, false, false])
185 );
186 }
187
188 #[test]
189 fn varbinview_compare() {
190 let array = VarBinArray::from_iter(
191 [Some(b"abc".to_vec()), None, Some(b"def".to_vec())],
192 DType::Binary(Nullability::Nullable),
193 );
194 let vbv = VarBinViewArray::from_iter(
195 [None, None, Some(b"def".to_vec())],
196 DType::Binary(Nullability::Nullable),
197 );
198 let result = array
199 .to_array()
200 .binary(vbv.to_array(), Operator::Eq)
201 .unwrap()
202 .to_bool();
203
204 assert_eq!(
205 result.validity_mask().unwrap().to_bit_buffer(),
206 BitBuffer::from_iter([false, false, true])
207 );
208 assert_eq!(
209 result.to_bit_buffer(),
210 BitBuffer::from_iter([false, true, true])
211 );
212 }
213}
214
215#[cfg(test)]
216mod tests {
217 use crate::Array;
218 use crate::arrays::ConstantArray;
219 use crate::arrays::VarBinArray;
220 use crate::builtins::ArrayBuiltins;
221 use crate::dtype::DType;
222 use crate::dtype::Nullability;
223 use crate::scalar::Scalar;
224 use crate::scalar_fn::fns::operators::Operator;
225
226 #[test]
227 fn test_null_compare() {
228 let arr = VarBinArray::from_iter([Some("h")], DType::Utf8(Nullability::NonNullable));
229
230 let const_ = ConstantArray::new(Scalar::utf8("", Nullability::Nullable), 1);
231
232 assert_eq!(
233 arr.to_array()
234 .binary(const_.to_array(), Operator::Eq)
235 .unwrap()
236 .dtype(),
237 &DType::Bool(Nullability::Nullable)
238 );
239 }
240}