ovr commented on code in PR #2549: URL: https://github.com/apache/arrow-datafusion/pull/2549#discussion_r876413237
########## datafusion/physical-expr/src/expressions/any.rs: ########## @@ -0,0 +1,674 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Any expression + +use std::any::Any; +use std::sync::Arc; + +use arrow::array::{ + BooleanArray, Int16Array, Int32Array, Int64Array, Int8Array, ListArray, + PrimitiveArray, UInt16Array, UInt32Array, UInt64Array, UInt8Array, +}; +use arrow::datatypes::ArrowPrimitiveType; +use arrow::{ + datatypes::{DataType, Schema}, + record_batch::RecordBatch, +}; + +use crate::expressions::try_cast; +use crate::PhysicalExpr; +use arrow::array::*; + +use datafusion_common::{DataFusionError, Result}; +use datafusion_expr::{ColumnarValue, Operator}; + +macro_rules! compare_op_scalar { + ($LEFT: expr, $LIST_VALUES:expr, $OP:expr, $LIST_VALUES_TYPE:ty, $LIST_FROM_SCALAR: expr) => {{ + let mut builder = BooleanBuilder::new($LEFT.len()); + + if $LIST_FROM_SCALAR { + for i in 0..$LEFT.len() { + if $LEFT.is_null(i) { + builder.append_null()?; + } else { + if $LIST_VALUES.is_null(0) { + builder.append_null()?; + } else { + builder.append_value($OP( + $LEFT.value(i), + $LIST_VALUES + .value(0) + .as_any() + .downcast_ref::<$LIST_VALUES_TYPE>() + .unwrap(), + ))?; + } + } + } + } else { + for i in 0..$LEFT.len() { + if $LEFT.is_null(i) { + builder.append_null()?; + } else { + if $LIST_VALUES.is_null(i) { + builder.append_null()?; + } else { + builder.append_value($OP( + $LEFT.value(i), + $LIST_VALUES + .value(i) + .as_any() + .downcast_ref::<$LIST_VALUES_TYPE>() + .unwrap(), + ))?; + } + } + } + } + + Ok(builder.finish()) + }}; +} + +macro_rules! make_primitive { + ($VALUES:expr, $IN_VALUES:expr, $NEGATED:expr, $TYPE:ident, $LIST_FROM_SCALAR: expr) => {{ + let left = $VALUES.as_any().downcast_ref::<$TYPE>().expect(&format!( + "Unable to downcast values to {}", + stringify!($TYPE) + )); + + if $NEGATED { + Ok(ColumnarValue::Array(Arc::new(neq_primitive( + left, + $IN_VALUES, + $LIST_FROM_SCALAR, + )?))) + } else { + Ok(ColumnarValue::Array(Arc::new(eq_primitive( + left, + $IN_VALUES, + $LIST_FROM_SCALAR, + )?))) + } + }}; +} + +fn eq_primitive<T: ArrowPrimitiveType>( + array: &PrimitiveArray<T>, + list: &ListArray, + list_from_scalar: bool, +) -> Result<BooleanArray> { + compare_op_scalar!( + array, + list, + |x, v: &PrimitiveArray<T>| v.values().contains(&x), + PrimitiveArray<T>, + list_from_scalar + ) +} + +fn neq_primitive<T: ArrowPrimitiveType>( + array: &PrimitiveArray<T>, + list: &ListArray, + list_from_scalar: bool, +) -> Result<BooleanArray> { + compare_op_scalar!( + array, + list, + |x, v: &PrimitiveArray<T>| !v.values().contains(&x), + PrimitiveArray<T>, + list_from_scalar + ) +} + +fn eq_bool( + array: &BooleanArray, + list: &ListArray, + list_from_scalar: bool, +) -> Result<BooleanArray> { + compare_op_scalar!( + array, + list, + |x, v: &BooleanArray| unsafe { + for i in 0..v.len() { + if v.value_unchecked(i) == x { + return true; + } + } + + false + }, + BooleanArray, + list_from_scalar + ) +} + +fn neq_bool( + array: &BooleanArray, + list: &ListArray, + list_from_scalar: bool, +) -> Result<BooleanArray> { + compare_op_scalar!( + array, + list, + |x, v: &BooleanArray| unsafe { + for i in 0..v.len() { + if v.value_unchecked(i) == x { + return false; + } + } + + true + }, + BooleanArray, + list_from_scalar + ) +} + +fn eq_utf8<OffsetSize: OffsetSizeTrait>( + array: &GenericStringArray<OffsetSize>, + list: &ListArray, + list_from_scalar: bool, +) -> Result<BooleanArray> { + compare_op_scalar!( + array, + list, + |x, v: &GenericStringArray<OffsetSize>| unsafe { + for i in 0..v.len() { + if v.value_unchecked(i) == x { + return true; + } + } + + false + }, + GenericStringArray<OffsetSize>, + list_from_scalar + ) +} + +fn neq_utf8<OffsetSize: OffsetSizeTrait>( + array: &GenericStringArray<OffsetSize>, + list: &ListArray, + list_from_scalar: bool, +) -> Result<BooleanArray> { + compare_op_scalar!( + array, + list, + |x, v: &GenericStringArray<OffsetSize>| unsafe { + for i in 0..v.len() { + if v.value_unchecked(i) == x { + return false; + } + } + + true + }, + GenericStringArray<OffsetSize>, + list_from_scalar + ) +} + +/// AnyExpr +#[derive(Debug)] +pub struct AnyExpr { + value: Arc<dyn PhysicalExpr>, + op: Operator, + list: Arc<dyn PhysicalExpr>, +} + +impl AnyExpr { + /// Create a new Any expression + pub fn new( + value: Arc<dyn PhysicalExpr>, + op: Operator, + list: Arc<dyn PhysicalExpr>, + ) -> Self { + Self { value, op, list } + } + + /// Compare for specific utf8 types + fn compare_utf8<T: OffsetSizeTrait>( + &self, + array: ArrayRef, + list: &ListArray, + negated: bool, + list_from_scalar: bool, + ) -> Result<ColumnarValue> { + let array = array + .as_any() + .downcast_ref::<GenericStringArray<T>>() + .unwrap(); + + if negated { + Ok(ColumnarValue::Array(Arc::new(neq_utf8( + array, + list, + list_from_scalar, + )?))) + } else { + Ok(ColumnarValue::Array(Arc::new(eq_utf8( + array, + list, + list_from_scalar, + )?))) + } + } + + /// Get the left side of the binary expression + pub fn left(&self) -> &Arc<dyn PhysicalExpr> { + &self.value + } + + /// Get the right side of the binary expression + pub fn right(&self) -> &Arc<dyn PhysicalExpr> { + &self.list + } + + /// Get the operator for this binary expression + pub fn op(&self) -> &Operator { + &self.op + } + + /// Compare for specific utf8 types + fn compare_bool( + &self, + array: ArrayRef, + list: &ListArray, + negated: bool, + list_from_scalar: bool, + ) -> Result<ColumnarValue> { + let array = array.as_any().downcast_ref::<BooleanArray>().unwrap(); + + if negated { + Ok(ColumnarValue::Array(Arc::new(neq_bool( + array, + list, + list_from_scalar, + )?))) + } else { + Ok(ColumnarValue::Array(Arc::new(eq_bool( + array, + list, + list_from_scalar, + )?))) + } + } +} + +impl std::fmt::Display for AnyExpr { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "{} {} ANY({})", self.value, self.op, self.list) + } +} + +impl PhysicalExpr for AnyExpr { + /// Return a reference to Any that can be used for downcasting + fn as_any(&self) -> &dyn Any { + self + } + + fn data_type(&self, _input_schema: &Schema) -> Result<DataType> { + Ok(DataType::Boolean) + } + + fn nullable(&self, input_schema: &Schema) -> Result<bool> { + self.value.nullable(input_schema) + } + + fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> { + let value = match self.value.evaluate(batch)? { + ColumnarValue::Array(array) => array, + ColumnarValue::Scalar(scalar) => scalar.to_array(), + }; Review Comment: > I haven't reviewed this code super carefully but I wonder what you think about reusing more of the code for InList? Probably, the nearest operator will be `ALL`, but it's not implemented right now. I tried to reuse the code of `InList`, but come to the decision that it will be easier/correct to combine it with ANY in the future. > It seems like the implementations of x IN (<expr>, <expr>) and x ANY (<expr>) are almost exactly the same except for the fact that the the x = ANY(<expr>) has the list as a single <expr> ? Nope, because it supports more operators: `<`, `<=`, `>`, `>=` (it's not implemented in this PR, but anyway). > I mention this as it is likely the IN / NOT IN are more optimized (use a hashset for testing, for example) as well as already written. Yes, but IN supports only the vector of scalars in DF. It's not the same as ANY, because it supports List (real column) or scalar. For example `SELECT left, values FROM table`: ```` left | right LIst(Int64) - another logic is required 1. | [1,2,3] - ArrayRef = PrimitiveArray<Int64> - another logic is requied 2. |. [2,3,4] 3. |. [4,5,6] 4. | [4,5,6] 5. |. [4,5,6] ```` In the case of using the whole column, it is required to use another handling of interacting on values ☝️ . Probably here, will be more correct to go by steps: - Support more operators - Introduce `ALL` operator + extract the same logic with `ANY`. Thanks -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
