datafusion_physical_expr/expressions/
is_null.rs1use std::hash::Hash;
21use std::{any::Any, sync::Arc};
22
23use crate::PhysicalExpr;
24use arrow::{
25 datatypes::{DataType, Schema},
26 record_batch::RecordBatch,
27};
28use datafusion_common::Result;
29use datafusion_common::ScalarValue;
30use datafusion_expr::ColumnarValue;
31
32#[derive(Debug, Eq)]
34pub struct IsNullExpr {
35 arg: Arc<dyn PhysicalExpr>,
37}
38
39impl PartialEq for IsNullExpr {
41 fn eq(&self, other: &Self) -> bool {
42 self.arg.eq(&other.arg)
43 }
44}
45
46impl Hash for IsNullExpr {
47 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
48 self.arg.hash(state);
49 }
50}
51
52impl IsNullExpr {
53 pub fn new(arg: Arc<dyn PhysicalExpr>) -> Self {
55 Self { arg }
56 }
57
58 pub fn arg(&self) -> &Arc<dyn PhysicalExpr> {
60 &self.arg
61 }
62}
63
64impl std::fmt::Display for IsNullExpr {
65 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
66 write!(f, "{} IS NULL", self.arg)
67 }
68}
69
70impl PhysicalExpr for IsNullExpr {
71 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) => Ok(ColumnarValue::Array(Arc::new(
88 arrow::compute::is_null(&array)?,
89 ))),
90 ColumnarValue::Scalar(scalar) => Ok(ColumnarValue::Scalar(
91 ScalarValue::Boolean(Some(scalar.is_null())),
92 )),
93 }
94 }
95
96 fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
97 vec![&self.arg]
98 }
99
100 fn with_new_children(
101 self: Arc<Self>,
102 children: Vec<Arc<dyn PhysicalExpr>>,
103 ) -> Result<Arc<dyn PhysicalExpr>> {
104 Ok(Arc::new(IsNullExpr::new(Arc::clone(&children[0]))))
105 }
106
107 fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 self.arg.fmt_sql(f)?;
109 write!(f, " IS NULL")
110 }
111}
112
113pub fn is_null(arg: Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>> {
115 Ok(Arc::new(IsNullExpr::new(arg)))
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121 use crate::expressions::col;
122 use arrow::array::{
123 Array, BooleanArray, Float64Array, Int32Array, StringArray, UnionArray,
124 };
125 use arrow::buffer::ScalarBuffer;
126 use arrow::datatypes::*;
127 use datafusion_common::cast::as_boolean_array;
128 use datafusion_physical_expr_common::physical_expr::fmt_sql;
129
130 #[test]
131 fn is_null_op() -> Result<()> {
132 let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
133 let a = StringArray::from(vec![Some("foo"), None]);
134
135 let expr = is_null(col("a", &schema)?).unwrap();
137 let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;
138
139 let result = expr
140 .evaluate(&batch)?
141 .into_array(batch.num_rows())
142 .expect("Failed to convert to array");
143 let result =
144 as_boolean_array(&result).expect("failed to downcast to BooleanArray");
145
146 let expected = &BooleanArray::from(vec![false, true]);
147
148 assert_eq!(expected, result);
149
150 Ok(())
151 }
152
153 fn union_fields() -> UnionFields {
154 [
155 (0, Arc::new(Field::new("A", DataType::Int32, true))),
156 (1, Arc::new(Field::new("B", DataType::Float64, true))),
157 (2, Arc::new(Field::new("C", DataType::Utf8, true))),
158 ]
159 .into_iter()
160 .collect()
161 }
162
163 #[test]
164 fn sparse_union_is_null() {
165 let int_array =
167 Int32Array::from(vec![Some(1), None, None, None, None, None, None]);
168 let float_array =
169 Float64Array::from(vec![None, None, Some(1.1), Some(1.2), None, None, None]);
170 let str_array =
171 StringArray::from(vec![None, None, None, None, None, None, Some("a")]);
172 let type_ids = [0, 0, 1, 1, 1, 2, 2]
173 .into_iter()
174 .collect::<ScalarBuffer<i8>>();
175
176 let children = vec![
177 Arc::new(int_array) as Arc<dyn Array>,
178 Arc::new(float_array),
179 Arc::new(str_array),
180 ];
181
182 let array =
183 UnionArray::try_new(union_fields(), type_ids, None, children).unwrap();
184
185 let result = arrow::compute::is_null(&array).unwrap();
186
187 let expected =
188 &BooleanArray::from(vec![false, true, false, false, true, true, false]);
189 assert_eq!(expected, &result);
190 }
191
192 #[test]
193 fn dense_union_is_null() {
194 let int_array = Int32Array::from(vec![Some(1), None]);
196 let float_array = Float64Array::from(vec![Some(3.2), None]);
197 let str_array = StringArray::from(vec![Some("a"), None]);
198 let type_ids = [0, 0, 1, 1, 2, 2].into_iter().collect::<ScalarBuffer<i8>>();
199 let offsets = [0, 1, 0, 1, 0, 1]
200 .into_iter()
201 .collect::<ScalarBuffer<i32>>();
202
203 let children = vec![
204 Arc::new(int_array) as Arc<dyn Array>,
205 Arc::new(float_array),
206 Arc::new(str_array),
207 ];
208
209 let array =
210 UnionArray::try_new(union_fields(), type_ids, Some(offsets), children)
211 .unwrap();
212
213 let result = arrow::compute::is_null(&array).unwrap();
214
215 let expected = &BooleanArray::from(vec![false, true, false, true, false, true]);
216 assert_eq!(expected, &result);
217 }
218
219 #[test]
220 fn test_fmt_sql() -> Result<()> {
221 let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
222
223 let expr = is_null(col("a", &schema)?).unwrap();
225 let display_string = expr.to_string();
226 assert_eq!(display_string, "a@0 IS NULL");
227 let sql_string = fmt_sql(expr.as_ref()).to_string();
228 assert_eq!(sql_string, "a IS NULL");
229
230 Ok(())
231 }
232}