datafusion_physical_expr/expressions/
is_not_null.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! IS NOT NULL expression
19
20use crate::PhysicalExpr;
21use arrow::datatypes::FieldRef;
22use arrow::{
23    datatypes::{DataType, Schema},
24    record_batch::RecordBatch,
25};
26use datafusion_common::Result;
27use datafusion_common::ScalarValue;
28use datafusion_expr::ColumnarValue;
29use std::hash::Hash;
30use std::{any::Any, sync::Arc};
31
32/// IS NOT NULL expression
33#[derive(Debug, Eq)]
34pub struct IsNotNullExpr {
35    /// The input expression
36    arg: Arc<dyn PhysicalExpr>,
37}
38
39// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
40impl PartialEq for IsNotNullExpr {
41    fn eq(&self, other: &Self) -> bool {
42        self.arg.eq(&other.arg)
43    }
44}
45
46impl Hash for IsNotNullExpr {
47    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
48        self.arg.hash(state);
49    }
50}
51
52impl IsNotNullExpr {
53    /// Create new not expression
54    pub fn new(arg: Arc<dyn PhysicalExpr>) -> Self {
55        Self { arg }
56    }
57
58    /// Get the input expression
59    pub fn arg(&self) -> &Arc<dyn PhysicalExpr> {
60        &self.arg
61    }
62}
63
64impl std::fmt::Display for IsNotNullExpr {
65    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
66        write!(f, "{} IS NOT NULL", self.arg)
67    }
68}
69
70impl PhysicalExpr for IsNotNullExpr {
71    /// Return a reference to Any that can be used for downcasting
72    fn as_any(&self) -> &dyn Any {
73        self
74    }
75
76    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
77        Ok(DataType::Boolean)
78    }
79
80    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
81        Ok(false)
82    }
83
84    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
85        let arg = self.arg.evaluate(batch)?;
86        match arg {
87            ColumnarValue::Array(array) => {
88                let is_not_null = arrow::compute::is_not_null(&array)?;
89                Ok(ColumnarValue::Array(Arc::new(is_not_null)))
90            }
91            ColumnarValue::Scalar(scalar) => Ok(ColumnarValue::Scalar(
92                ScalarValue::Boolean(Some(!scalar.is_null())),
93            )),
94        }
95    }
96
97    fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> {
98        self.arg.return_field(input_schema)
99    }
100
101    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
102        vec![&self.arg]
103    }
104
105    fn with_new_children(
106        self: Arc<Self>,
107        children: Vec<Arc<dyn PhysicalExpr>>,
108    ) -> Result<Arc<dyn PhysicalExpr>> {
109        Ok(Arc::new(IsNotNullExpr::new(Arc::clone(&children[0]))))
110    }
111
112    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        self.arg.fmt_sql(f)?;
114        write!(f, " IS NOT NULL")
115    }
116}
117
118/// Create an IS NOT NULL expression
119pub fn is_not_null(arg: Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>> {
120    Ok(Arc::new(IsNotNullExpr::new(arg)))
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use crate::expressions::col;
127    use arrow::array::{
128        Array, BooleanArray, Float64Array, Int32Array, StringArray, UnionArray,
129    };
130    use arrow::buffer::ScalarBuffer;
131    use arrow::datatypes::*;
132    use datafusion_common::cast::as_boolean_array;
133    use datafusion_physical_expr_common::physical_expr::fmt_sql;
134
135    #[test]
136    fn is_not_null_op() -> Result<()> {
137        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
138        let a = StringArray::from(vec![Some("foo"), None]);
139        let expr = is_not_null(col("a", &schema)?).unwrap();
140        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;
141
142        // expression: "a is not null"
143        let result = expr
144            .evaluate(&batch)?
145            .into_array(batch.num_rows())
146            .expect("Failed to convert to array");
147        let result =
148            as_boolean_array(&result).expect("failed to downcast to BooleanArray");
149
150        let expected = &BooleanArray::from(vec![true, false]);
151
152        assert_eq!(expected, result);
153
154        Ok(())
155    }
156
157    #[test]
158    fn union_is_not_null_op() {
159        // union of [{A=1}, {A=}, {B=1.1}, {B=1.2}, {B=}]
160        let int_array = Int32Array::from(vec![Some(1), None, None, None, None]);
161        let float_array =
162            Float64Array::from(vec![None, None, Some(1.1), Some(1.2), None]);
163        let type_ids = [0, 0, 1, 1, 1].into_iter().collect::<ScalarBuffer<i8>>();
164
165        let children = vec![Arc::new(int_array) as Arc<dyn Array>, Arc::new(float_array)];
166
167        let union_fields: UnionFields = [
168            (0, Arc::new(Field::new("A", DataType::Int32, true))),
169            (1, Arc::new(Field::new("B", DataType::Float64, true))),
170        ]
171        .into_iter()
172        .collect();
173
174        let array =
175            UnionArray::try_new(union_fields.clone(), type_ids, None, children).unwrap();
176
177        let field = Field::new(
178            "my_union",
179            DataType::Union(union_fields, UnionMode::Sparse),
180            true,
181        );
182
183        let schema = Schema::new(vec![field]);
184        let expr = is_not_null(col("my_union", &schema).unwrap()).unwrap();
185        let batch =
186            RecordBatch::try_new(Arc::new(schema), vec![Arc::new(array)]).unwrap();
187
188        // expression: "a is not null"
189        let actual = expr
190            .evaluate(&batch)
191            .unwrap()
192            .into_array(batch.num_rows())
193            .expect("Failed to convert to array");
194        let actual = as_boolean_array(&actual).unwrap();
195
196        let expected = &BooleanArray::from(vec![true, false, true, true, false]);
197
198        assert_eq!(expected, actual);
199    }
200
201    #[test]
202    fn test_fmt_sql() -> Result<()> {
203        let union_fields: UnionFields = [
204            (0, Arc::new(Field::new("A", DataType::Int32, true))),
205            (1, Arc::new(Field::new("B", DataType::Float64, true))),
206        ]
207        .into_iter()
208        .collect();
209
210        let field = Field::new(
211            "my_union",
212            DataType::Union(union_fields, UnionMode::Sparse),
213            true,
214        );
215
216        let schema = Schema::new(vec![field]);
217        let expr = is_not_null(col("my_union", &schema).unwrap()).unwrap();
218        let display_string = expr.to_string();
219        assert_eq!(display_string, "my_union@0 IS NOT NULL");
220        let sql_string = fmt_sql(expr.as_ref()).to_string();
221        assert_eq!(sql_string, "my_union IS NOT NULL");
222
223        Ok(())
224    }
225}