Skip to main content

datafusion_physical_expr/expressions/
is_null.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! IS NULL expression
6
7use crate::PhysicalExpr;
8use arrow::{
9    datatypes::{DataType, Schema},
10    record_batch::RecordBatch,
11};
12use datafusion_common::{Result, ScalarValue};
13use datafusion_expr::ColumnarValue;
14use std::hash::Hash;
15use std::sync::Arc;
16
17/// IS NULL expression
18#[derive(Debug, Eq)]
19pub struct IsNullExpr {
20    /// Input expression
21    arg: Arc<dyn PhysicalExpr>,
22}
23
24// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
25impl PartialEq for IsNullExpr {
26    fn eq(&self, other: &Self) -> bool {
27        self.arg.eq(&other.arg)
28    }
29}
30
31impl Hash for IsNullExpr {
32    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
33        self.arg.hash(state);
34    }
35}
36
37impl IsNullExpr {
38    /// Create new not expression
39    pub fn new(arg: Arc<dyn PhysicalExpr>) -> Self {
40        Self { arg }
41    }
42
43    /// Get the input expression
44    pub fn arg(&self) -> &Arc<dyn PhysicalExpr> {
45        &self.arg
46    }
47}
48
49impl std::fmt::Display for IsNullExpr {
50    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
51        write!(f, "{} IS NULL", self.arg)
52    }
53}
54
55impl PhysicalExpr for IsNullExpr {
56    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
57        Ok(DataType::Boolean)
58    }
59
60    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
61        Ok(false)
62    }
63
64    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
65        let arg = self.arg.evaluate(batch)?;
66        match arg {
67            ColumnarValue::Array(array) => Ok(ColumnarValue::Array(Arc::new(
68                arrow::compute::is_null(&array)?,
69            ))),
70            ColumnarValue::Scalar(scalar) => Ok(ColumnarValue::Scalar(
71                ScalarValue::Boolean(Some(scalar.is_null())),
72            )),
73        }
74    }
75
76    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
77        vec![&self.arg]
78    }
79
80    fn with_new_children(
81        self: Arc<Self>,
82        children: Vec<Arc<dyn PhysicalExpr>>,
83    ) -> Result<Arc<dyn PhysicalExpr>> {
84        Ok(Arc::new(IsNullExpr::new(Arc::clone(&children[0]))))
85    }
86
87    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        self.arg.fmt_sql(f)?;
89        write!(f, " IS NULL")
90    }
91
92    #[cfg(feature = "proto")]
93    fn try_to_proto(
94        &self,
95        ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
96    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
97        use datafusion_proto_models::protobuf;
98
99        let Self { arg } = self;
100        Ok(Some(protobuf::PhysicalExprNode {
101            expr_id: None,
102            expr_type: Some(protobuf::physical_expr_node::ExprType::IsNullExpr(
103                Box::new(protobuf::PhysicalIsNull {
104                    expr: Some(Box::new(ctx.encode_child(arg)?)),
105                }),
106            )),
107        }))
108    }
109}
110
111#[cfg(feature = "proto")]
112impl IsNullExpr {
113    /// Reconstruct an [`IsNullExpr`] from its protobuf representation.
114    pub fn try_from_proto(
115        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
116        ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
117    ) -> Result<Arc<dyn PhysicalExpr>> {
118        use datafusion_physical_expr_common::expect_expr_variant;
119        use datafusion_proto_models::protobuf;
120
121        let node = expect_expr_variant!(
122            node,
123            protobuf::physical_expr_node::ExprType::IsNullExpr,
124            "IsNullExpr",
125        );
126        let protobuf::PhysicalIsNull { expr } = node.as_ref();
127        let expr =
128            ctx.decode_required_expression(expr.as_deref(), "IsNullExpr", "expr")?;
129
130        Ok(Arc::new(IsNullExpr::new(expr)))
131    }
132}
133
134/// Create an IS NULL expression
135pub fn is_null(arg: Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>> {
136    Ok(Arc::new(IsNullExpr::new(arg)))
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use crate::expressions::col;
143    use arrow::array::{
144        Array, BooleanArray, Float64Array, Int32Array, StringArray, UnionArray,
145    };
146    use arrow::buffer::ScalarBuffer;
147    use arrow::datatypes::*;
148    use datafusion_common::cast::as_boolean_array;
149    use datafusion_physical_expr_common::physical_expr::fmt_sql;
150
151    #[test]
152    fn is_null_op() -> Result<()> {
153        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
154        let a = StringArray::from(vec![Some("foo"), None]);
155
156        // expression: "a is null"
157        let expr = is_null(col("a", &schema)?).unwrap();
158        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;
159
160        let result = expr
161            .evaluate(&batch)?
162            .into_array(batch.num_rows())
163            .expect("Failed to convert to array");
164        let result =
165            as_boolean_array(&result).expect("failed to downcast to BooleanArray");
166
167        let expected = &BooleanArray::from(vec![false, true]);
168
169        assert_eq!(expected, result);
170
171        Ok(())
172    }
173
174    fn union_fields() -> UnionFields {
175        [
176            (0, Arc::new(Field::new("A", DataType::Int32, true))),
177            (1, Arc::new(Field::new("B", DataType::Float64, true))),
178            (2, Arc::new(Field::new("C", DataType::Utf8, true))),
179        ]
180        .into_iter()
181        .collect()
182    }
183
184    #[test]
185    fn sparse_union_is_null() {
186        // union of [{A=1}, {A=}, {B=1.1}, {B=1.2}, {B=}, {C=}, {C="a"}]
187        let int_array =
188            Int32Array::from(vec![Some(1), None, None, None, None, None, None]);
189        let float_array =
190            Float64Array::from(vec![None, None, Some(1.1), Some(1.2), None, None, None]);
191        let str_array =
192            StringArray::from(vec![None, None, None, None, None, None, Some("a")]);
193        let type_ids = [0, 0, 1, 1, 1, 2, 2]
194            .into_iter()
195            .collect::<ScalarBuffer<i8>>();
196
197        let children = vec![
198            Arc::new(int_array) as Arc<dyn Array>,
199            Arc::new(float_array),
200            Arc::new(str_array),
201        ];
202
203        let array =
204            UnionArray::try_new(union_fields(), type_ids, None, children).unwrap();
205
206        let result = arrow::compute::is_null(&array).unwrap();
207
208        let expected =
209            &BooleanArray::from(vec![false, true, false, false, true, true, false]);
210        assert_eq!(expected, &result);
211    }
212
213    #[test]
214    fn dense_union_is_null() {
215        // union of [{A=1}, {A=}, {B=3.2}, {B=}, {C="a"}, {C=}]
216        let int_array = Int32Array::from(vec![Some(1), None]);
217        let float_array = Float64Array::from(vec![Some(3.2), None]);
218        let str_array = StringArray::from(vec![Some("a"), None]);
219        let type_ids = [0, 0, 1, 1, 2, 2].into_iter().collect::<ScalarBuffer<i8>>();
220        let offsets = [0, 1, 0, 1, 0, 1]
221            .into_iter()
222            .collect::<ScalarBuffer<i32>>();
223
224        let children = vec![
225            Arc::new(int_array) as Arc<dyn Array>,
226            Arc::new(float_array),
227            Arc::new(str_array),
228        ];
229
230        let array =
231            UnionArray::try_new(union_fields(), type_ids, Some(offsets), children)
232                .unwrap();
233
234        let result = arrow::compute::is_null(&array).unwrap();
235
236        let expected = &BooleanArray::from(vec![false, true, false, true, false, true]);
237        assert_eq!(expected, &result);
238    }
239
240    #[test]
241    fn test_fmt_sql() -> Result<()> {
242        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
243
244        // expression: "a is null"
245        let expr = is_null(col("a", &schema)?).unwrap();
246        let display_string = expr.to_string();
247        assert_eq!(display_string, "a@0 IS NULL");
248        let sql_string = fmt_sql(expr.as_ref()).to_string();
249        assert_eq!(sql_string, "a IS NULL");
250
251        Ok(())
252    }
253}
254
255#[cfg(all(test, feature = "proto"))]
256mod proto_tests {
257    use super::*;
258    use crate::expressions::{Column, col};
259    use crate::proto_test_util::{
260        StubDecoder, StubEncoder, UnreachableDecoder, column_node,
261    };
262    use arrow::datatypes::Field;
263    use datafusion_common::DataFusionError;
264    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
265    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
266    use datafusion_proto_models::protobuf::{
267        PhysicalExprNode, PhysicalIsNull, physical_expr_node,
268    };
269
270    fn is_null_node(expr: Option<Box<PhysicalExprNode>>) -> PhysicalExprNode {
271        PhysicalExprNode {
272            expr_id: None,
273            expr_type: Some(physical_expr_node::ExprType::IsNullExpr(Box::new(
274                PhysicalIsNull { expr },
275            ))),
276        }
277    }
278
279    fn is_null_fixture() -> IsNullExpr {
280        let schema = Schema::new(vec![Field::new("a", DataType::Int64, true)]);
281        IsNullExpr::new(col("a", &schema).unwrap())
282    }
283
284    #[test]
285    fn try_to_proto_encodes_is_null_expr() {
286        let is_null = is_null_fixture();
287        let encoder = StubEncoder::ok();
288        let ctx = PhysicalExprEncodeCtx::new(&encoder);
289
290        let node = is_null
291            .try_to_proto(&ctx)
292            .unwrap()
293            .expect("IsNullExpr should encode to Some(node)");
294
295        assert!(node.expr_id.is_none());
296        let is_null_node = match node.expr_type {
297            Some(physical_expr_node::ExprType::IsNullExpr(boxed)) => *boxed,
298            other => panic!("expected an IsNullExpr node, got {other:?}"),
299        };
300        assert!(is_null_node.expr.is_some());
301    }
302
303    #[test]
304    fn try_to_proto_propagates_expr_encode_error() {
305        let is_null = is_null_fixture();
306        let encoder = StubEncoder::failing_on(1);
307        let ctx = PhysicalExprEncodeCtx::new(&encoder);
308        let err = is_null.try_to_proto(&ctx).unwrap_err();
309        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
310    }
311
312    #[test]
313    fn try_from_proto_decodes_is_null_expr() {
314        let node = is_null_node(Some(Box::new(column_node("a"))));
315        let schema = Schema::empty();
316        let decoder = StubDecoder::ok();
317        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
318
319        let decoded = IsNullExpr::try_from_proto(&node, &ctx).unwrap();
320        let is_null = decoded
321            .downcast_ref::<IsNullExpr>()
322            .expect("decoded expr should be an IsNullExpr");
323        assert!(is_null.arg().downcast_ref::<Column>().is_some());
324    }
325
326    #[test]
327    fn try_from_proto_rejects_non_is_null_node() {
328        let node = column_node("a");
329        let schema = Schema::empty();
330        let decoder = UnreachableDecoder;
331        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
332        let err = IsNullExpr::try_from_proto(&node, &ctx).unwrap_err();
333        assert!(
334            matches!(err, DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a IsNullExpr"))
335        );
336    }
337
338    #[test]
339    fn try_from_proto_rejects_missing_expr() {
340        let node = is_null_node(None);
341        let schema = Schema::empty();
342        let decoder = UnreachableDecoder;
343        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
344        let err = IsNullExpr::try_from_proto(&node, &ctx).unwrap_err();
345        assert!(
346            matches!(err, DataFusionError::Internal(msg) if msg.contains("IsNullExpr is missing required field 'expr'"))
347        );
348    }
349
350    #[test]
351    fn try_from_proto_propagates_expr_decode_error() {
352        let node = is_null_node(Some(Box::new(column_node("a"))));
353        let schema = Schema::empty();
354        let decoder = StubDecoder::failing_on(1);
355        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
356        let err = IsNullExpr::try_from_proto(&node, &ctx).unwrap_err();
357        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
358    }
359}