datafusion_physical_expr/expressions/
is_not_null.rs1use 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#[derive(Debug, Eq)]
19pub struct IsNotNullExpr {
20 arg: Arc<dyn PhysicalExpr>,
22}
23
24impl PartialEq for IsNotNullExpr {
26 fn eq(&self, other: &Self) -> bool {
27 self.arg.eq(&other.arg)
28 }
29}
30
31impl Hash for IsNotNullExpr {
32 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
33 self.arg.hash(state);
34 }
35}
36
37impl IsNotNullExpr {
38 pub fn new(arg: Arc<dyn PhysicalExpr>) -> Self {
40 Self { arg }
41 }
42
43 pub fn arg(&self) -> &Arc<dyn PhysicalExpr> {
45 &self.arg
46 }
47}
48
49impl std::fmt::Display for IsNotNullExpr {
50 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
51 write!(f, "{} IS NOT NULL", self.arg)
52 }
53}
54
55impl PhysicalExpr for IsNotNullExpr {
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) => {
68 let is_not_null = arrow::compute::is_not_null(&array)?;
69 Ok(ColumnarValue::Array(Arc::new(is_not_null)))
70 }
71 ColumnarValue::Scalar(scalar) => Ok(ColumnarValue::Scalar(
72 ScalarValue::Boolean(Some(!scalar.is_null())),
73 )),
74 }
75 }
76
77 fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
78 vec![&self.arg]
79 }
80
81 fn with_new_children(
82 self: Arc<Self>,
83 children: Vec<Arc<dyn PhysicalExpr>>,
84 ) -> Result<Arc<dyn PhysicalExpr>> {
85 Ok(Arc::new(IsNotNullExpr::new(Arc::clone(&children[0]))))
86 }
87
88 fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89 self.arg.fmt_sql(f)?;
90 write!(f, " IS NOT NULL")
91 }
92
93 #[cfg(feature = "proto")]
94 fn try_to_proto(
95 &self,
96 ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
97 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
98 use datafusion_proto_models::protobuf;
99
100 let Self { arg } = self;
101 Ok(Some(protobuf::PhysicalExprNode {
102 expr_id: None,
103 expr_type: Some(protobuf::physical_expr_node::ExprType::IsNotNullExpr(
104 Box::new(protobuf::PhysicalIsNotNull {
105 expr: Some(Box::new(ctx.encode_child(arg)?)),
106 }),
107 )),
108 }))
109 }
110}
111
112#[cfg(feature = "proto")]
113impl IsNotNullExpr {
114 pub fn try_from_proto(
116 node: &datafusion_proto_models::protobuf::PhysicalExprNode,
117 ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
118 ) -> Result<Arc<dyn PhysicalExpr>> {
119 use datafusion_physical_expr_common::expect_expr_variant;
120 use datafusion_proto_models::protobuf;
121
122 let node = expect_expr_variant!(
123 node,
124 protobuf::physical_expr_node::ExprType::IsNotNullExpr,
125 "IsNotNullExpr",
126 );
127 let protobuf::PhysicalIsNotNull { expr } = node.as_ref();
128 let expr =
129 ctx.decode_required_expression(expr.as_deref(), "IsNotNullExpr", "expr")?;
130
131 Ok(Arc::new(IsNotNullExpr::new(expr)))
132 }
133}
134
135pub fn is_not_null(arg: Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>> {
137 Ok(Arc::new(IsNotNullExpr::new(arg)))
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143 use crate::expressions::col;
144 use arrow::array::{
145 Array, BooleanArray, Float64Array, Int32Array, StringArray, UnionArray,
146 };
147 use arrow::buffer::ScalarBuffer;
148 use arrow::datatypes::*;
149 use datafusion_common::cast::as_boolean_array;
150 use datafusion_physical_expr_common::physical_expr::fmt_sql;
151
152 #[test]
153 fn is_not_null_op() -> Result<()> {
154 let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
155 let a = StringArray::from(vec![Some("foo"), None]);
156 let expr = is_not_null(col("a", &schema)?).unwrap();
157 let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;
158
159 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![true, false]);
168
169 assert_eq!(expected, result);
170
171 Ok(())
172 }
173
174 #[test]
175 fn union_is_not_null_op() {
176 let int_array = Int32Array::from(vec![Some(1), None, None, None, None]);
178 let float_array =
179 Float64Array::from(vec![None, None, Some(1.1), Some(1.2), None]);
180 let type_ids = [0, 0, 1, 1, 1].into_iter().collect::<ScalarBuffer<i8>>();
181
182 let children = vec![Arc::new(int_array) as Arc<dyn Array>, Arc::new(float_array)];
183
184 let union_fields: UnionFields = [
185 (0, Arc::new(Field::new("A", DataType::Int32, true))),
186 (1, Arc::new(Field::new("B", DataType::Float64, true))),
187 ]
188 .into_iter()
189 .collect();
190
191 let array =
192 UnionArray::try_new(union_fields.clone(), type_ids, None, children).unwrap();
193
194 let field = Field::new(
195 "my_union",
196 DataType::Union(union_fields, UnionMode::Sparse),
197 true,
198 );
199
200 let schema = Schema::new(vec![field]);
201 let expr = is_not_null(col("my_union", &schema).unwrap()).unwrap();
202 let batch =
203 RecordBatch::try_new(Arc::new(schema), vec![Arc::new(array)]).unwrap();
204
205 let actual = expr
207 .evaluate(&batch)
208 .unwrap()
209 .into_array(batch.num_rows())
210 .expect("Failed to convert to array");
211 let actual = as_boolean_array(&actual).unwrap();
212
213 let expected = &BooleanArray::from(vec![true, false, true, true, false]);
214
215 assert_eq!(expected, actual);
216 }
217
218 #[test]
219 fn test_fmt_sql() -> Result<()> {
220 let union_fields: UnionFields = [
221 (0, Arc::new(Field::new("A", DataType::Int32, true))),
222 (1, Arc::new(Field::new("B", DataType::Float64, true))),
223 ]
224 .into_iter()
225 .collect();
226
227 let field = Field::new(
228 "my_union",
229 DataType::Union(union_fields, UnionMode::Sparse),
230 true,
231 );
232
233 let schema = Schema::new(vec![field]);
234 let expr = is_not_null(col("my_union", &schema).unwrap()).unwrap();
235 let display_string = expr.to_string();
236 assert_eq!(display_string, "my_union@0 IS NOT NULL");
237 let sql_string = fmt_sql(expr.as_ref()).to_string();
238 assert_eq!(sql_string, "my_union IS NOT NULL");
239
240 Ok(())
241 }
242}
243
244#[cfg(all(test, feature = "proto"))]
245mod proto_tests {
246 use super::*;
247 use crate::expressions::{Column, col};
248 use crate::proto_test_util::{
249 StubDecoder, StubEncoder, UnreachableDecoder, column_node,
250 };
251 use arrow::datatypes::Field;
252 use datafusion_common::DataFusionError;
253 use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
254 use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
255 use datafusion_proto_models::protobuf::{
256 PhysicalExprNode, PhysicalIsNotNull, physical_expr_node,
257 };
258
259 fn is_not_null_node(expr: Option<Box<PhysicalExprNode>>) -> PhysicalExprNode {
260 PhysicalExprNode {
261 expr_id: None,
262 expr_type: Some(physical_expr_node::ExprType::IsNotNullExpr(Box::new(
263 PhysicalIsNotNull { expr },
264 ))),
265 }
266 }
267
268 fn is_not_null_fixture() -> IsNotNullExpr {
269 let schema = Schema::new(vec![Field::new("a", DataType::Int64, true)]);
270 IsNotNullExpr::new(col("a", &schema).unwrap())
271 }
272
273 #[test]
274 fn try_to_proto_encodes_is_not_null_expr() {
275 let is_not_null = is_not_null_fixture();
276 let encoder = StubEncoder::ok();
277 let ctx = PhysicalExprEncodeCtx::new(&encoder);
278
279 let node = is_not_null
280 .try_to_proto(&ctx)
281 .unwrap()
282 .expect("IsNotNullExpr should encode to Some(node)");
283
284 assert!(node.expr_id.is_none());
285 let is_not_null_node = match node.expr_type {
286 Some(physical_expr_node::ExprType::IsNotNullExpr(boxed)) => *boxed,
287 other => panic!("expected an IsNotNullExpr node, got {other:?}"),
288 };
289 assert!(is_not_null_node.expr.is_some());
290 }
291
292 #[test]
293 fn try_to_proto_propagates_expr_encode_error() {
294 let is_not_null = is_not_null_fixture();
295 let encoder = StubEncoder::failing_on(1);
296 let ctx = PhysicalExprEncodeCtx::new(&encoder);
297 let err = is_not_null.try_to_proto(&ctx).unwrap_err();
298 assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
299 }
300
301 #[test]
302 fn try_from_proto_decodes_is_not_null_expr() {
303 let node = is_not_null_node(Some(Box::new(column_node("a"))));
304 let schema = Schema::empty();
305 let decoder = StubDecoder::ok();
306 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
307
308 let decoded = IsNotNullExpr::try_from_proto(&node, &ctx).unwrap();
309 let is_not_null = decoded
310 .downcast_ref::<IsNotNullExpr>()
311 .expect("decoded expr should be an IsNotNullExpr");
312 assert!(is_not_null.arg().downcast_ref::<Column>().is_some());
313 }
314
315 #[test]
316 fn try_from_proto_rejects_non_is_not_null_node() {
317 let node = column_node("a");
318 let schema = Schema::empty();
319 let decoder = UnreachableDecoder;
320 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
321 let err = IsNotNullExpr::try_from_proto(&node, &ctx).unwrap_err();
322 assert!(
323 matches!(err, DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a IsNotNullExpr"))
324 );
325 }
326
327 #[test]
328 fn try_from_proto_rejects_missing_expr() {
329 let node = is_not_null_node(None);
330 let schema = Schema::empty();
331 let decoder = UnreachableDecoder;
332 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
333 let err = IsNotNullExpr::try_from_proto(&node, &ctx).unwrap_err();
334 assert!(
335 matches!(err, DataFusionError::Internal(msg) if msg.contains("IsNotNullExpr is missing required field 'expr'"))
336 );
337 }
338
339 #[test]
340 fn try_from_proto_propagates_expr_decode_error() {
341 let node = is_not_null_node(Some(Box::new(column_node("a"))));
342 let schema = Schema::empty();
343 let decoder = StubDecoder::failing_on(1);
344 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
345 let err = IsNotNullExpr::try_from_proto(&node, &ctx).unwrap_err();
346 assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
347 }
348}