datafusion_physical_expr/expressions/
not.rs1use std::fmt;
8use std::hash::Hash;
9use std::sync::Arc;
10
11use crate::PhysicalExpr;
12
13use arrow::datatypes::{DataType, FieldRef, Schema};
14use arrow::record_batch::RecordBatch;
15use datafusion_common::{Result, ScalarValue, cast::as_boolean_array, internal_err};
16use datafusion_expr::ColumnarValue;
17use datafusion_expr::interval_arithmetic::Interval;
18#[expect(deprecated)]
19use datafusion_expr::statistics::Distribution::{self, Bernoulli};
20
21#[derive(Debug, Eq)]
23pub struct NotExpr {
24 arg: Arc<dyn PhysicalExpr>,
26}
27
28impl PartialEq for NotExpr {
30 fn eq(&self, other: &Self) -> bool {
31 self.arg.eq(&other.arg)
32 }
33}
34
35impl Hash for NotExpr {
36 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
37 self.arg.hash(state);
38 }
39}
40
41impl NotExpr {
42 pub fn new(arg: Arc<dyn PhysicalExpr>) -> Self {
44 Self { arg }
45 }
46
47 pub fn arg(&self) -> &Arc<dyn PhysicalExpr> {
49 &self.arg
50 }
51}
52
53impl fmt::Display for NotExpr {
54 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55 write!(f, "NOT {}", self.arg)
56 }
57}
58
59impl PhysicalExpr for NotExpr {
60 fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
61 Ok(DataType::Boolean)
62 }
63
64 fn nullable(&self, input_schema: &Schema) -> Result<bool> {
65 self.arg.nullable(input_schema)
66 }
67
68 fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
69 match self.arg.evaluate(batch)? {
70 ColumnarValue::Array(array) => {
71 let array = as_boolean_array(&array)?;
72 Ok(ColumnarValue::Array(Arc::new(
73 arrow::compute::kernels::boolean::not(array)?,
74 )))
75 }
76 ColumnarValue::Scalar(scalar) => {
77 if scalar.is_null() {
78 return Ok(ColumnarValue::Scalar(ScalarValue::Boolean(None)));
79 }
80 let bool_value: bool = scalar.try_into()?;
81 Ok(ColumnarValue::Scalar(ScalarValue::from(!bool_value)))
82 }
83 }
84 }
85
86 fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> {
87 self.arg.return_field(input_schema)
88 }
89
90 fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
91 vec![&self.arg]
92 }
93
94 fn with_new_children(
95 self: Arc<Self>,
96 children: Vec<Arc<dyn PhysicalExpr>>,
97 ) -> Result<Arc<dyn PhysicalExpr>> {
98 Ok(Arc::new(NotExpr::new(Arc::clone(&children[0]))))
99 }
100
101 fn evaluate_bounds(&self, children: &[&Interval]) -> Result<Interval> {
102 children[0].not()
103 }
104
105 fn propagate_constraints(
106 &self,
107 interval: &Interval,
108 children: &[&Interval],
109 ) -> Result<Option<Vec<Interval>>> {
110 let complemented_interval = interval.not()?;
111
112 Ok(children[0]
113 .intersect(complemented_interval)?
114 .map(|result| vec![result]))
115 }
116
117 #[expect(deprecated)]
118 fn evaluate_statistics(&self, children: &[&Distribution]) -> Result<Distribution> {
119 match children[0] {
120 Bernoulli(b) => {
121 let p_value = b.p_value();
122 if p_value.is_null() {
123 Ok(children[0].clone())
124 } else {
125 let one = ScalarValue::new_one(&p_value.data_type())?;
126 Distribution::new_bernoulli(one.sub_checked(p_value)?)
127 }
128 }
129 _ => internal_err!("NotExpr can only operate on Boolean datatypes"),
130 }
131 }
132
133 #[expect(deprecated)]
134 fn propagate_statistics(
135 &self,
136 parent: &Distribution,
137 children: &[&Distribution],
138 ) -> Result<Option<Vec<Distribution>>> {
139 match (parent, children[0]) {
140 (Bernoulli(parent), Bernoulli(child)) => {
141 let parent_range = parent.range();
142 let result = if parent_range == Interval::TRUE {
143 if child.range() == Interval::TRUE {
144 None
145 } else {
146 Some(vec![Distribution::new_bernoulli(ScalarValue::new_zero(
147 &child.data_type(),
148 )?)?])
149 }
150 } else if parent_range == Interval::FALSE {
151 if child.range() == Interval::FALSE {
152 None
153 } else {
154 Some(vec![Distribution::new_bernoulli(ScalarValue::new_one(
155 &child.data_type(),
156 )?)?])
157 }
158 } else {
159 Some(vec![])
160 };
161 Ok(result)
162 }
163 _ => internal_err!("NotExpr can only operate on Boolean datatypes"),
164 }
165 }
166
167 fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 write!(f, "NOT ")?;
169 self.arg.fmt_sql(f)
170 }
171
172 #[cfg(feature = "proto")]
173 fn try_to_proto(
174 &self,
175 ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
176 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
177 use datafusion_proto_models::protobuf;
178
179 let Self { arg } = self;
180 Ok(Some(protobuf::PhysicalExprNode {
181 expr_id: None,
182 expr_type: Some(protobuf::physical_expr_node::ExprType::NotExpr(Box::new(
183 protobuf::PhysicalNot {
184 expr: Some(Box::new(ctx.encode_child(arg)?)),
185 },
186 ))),
187 }))
188 }
189}
190
191#[cfg(feature = "proto")]
192impl NotExpr {
193 pub fn try_from_proto(
195 node: &datafusion_proto_models::protobuf::PhysicalExprNode,
196 ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
197 ) -> Result<Arc<dyn PhysicalExpr>> {
198 use datafusion_physical_expr_common::expect_expr_variant;
199 use datafusion_proto_models::protobuf;
200
201 let not_expr = expect_expr_variant!(
202 node,
203 protobuf::physical_expr_node::ExprType::NotExpr,
204 "NotExpr",
205 );
206 let protobuf::PhysicalNot { expr } = not_expr.as_ref();
207 let expr = ctx.decode_required_expression(expr.as_deref(), "NotExpr", "expr")?;
208
209 Ok(Arc::new(NotExpr::new(expr)))
210 }
211}
212
213pub fn not(arg: Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>> {
215 Ok(Arc::new(NotExpr::new(arg)))
216}
217
218#[cfg(test)]
219mod tests {
220 use std::sync::LazyLock;
221
222 use super::*;
223 use crate::expressions::{Column, col};
224
225 use arrow::{array::BooleanArray, datatypes::*};
226 use datafusion_physical_expr_common::physical_expr::fmt_sql;
227
228 #[test]
229 fn neg_op() -> Result<()> {
230 let schema = schema();
231
232 let expr = not(col("a", &schema)?)?;
233 assert_eq!(expr.data_type(&schema)?, DataType::Boolean);
234 assert!(expr.nullable(&schema)?);
235
236 let input = BooleanArray::from(vec![Some(true), None, Some(false)]);
237 let expected = &BooleanArray::from(vec![Some(false), None, Some(true)]);
238
239 let batch = RecordBatch::try_new(schema, vec![Arc::new(input)])?;
240
241 let result = expr
242 .evaluate(&batch)?
243 .into_array(batch.num_rows())
244 .expect("Failed to convert to array");
245 let result =
246 as_boolean_array(&result).expect("failed to downcast to BooleanArray");
247 assert_eq!(result, expected);
248
249 Ok(())
250 }
251
252 #[test]
253 fn test_evaluate_bounds() -> Result<()> {
254 assert_evaluate_bounds(
260 Interval::make(Some(false), Some(true))?,
261 Interval::make(Some(false), Some(true))?,
262 )?;
263 assert_evaluate_bounds(
266 Interval::make(Some(true), Some(true))?,
267 Interval::make(Some(false), Some(false))?,
268 )?;
269 assert_evaluate_bounds(
270 Interval::make(Some(false), Some(false))?,
271 Interval::make(Some(true), Some(true))?,
272 )?;
273 Ok(())
274 }
275
276 fn assert_evaluate_bounds(
277 interval: Interval,
278 expected_interval: Interval,
279 ) -> Result<()> {
280 let not_expr = not(col("a", &schema())?)?;
281 assert_eq!(not_expr.evaluate_bounds(&[&interval])?, expected_interval);
282 Ok(())
283 }
284
285 #[test]
286 #[expect(deprecated)]
287 fn test_evaluate_statistics() -> Result<()> {
288 let _schema = &Schema::new(vec![Field::new("a", DataType::Boolean, false)]);
289 let a = Arc::new(Column::new("a", 0)) as _;
290 let expr = not(a)?;
291
292 assert!(
294 expr.evaluate_statistics(&[&Distribution::new_uniform(
295 Interval::make_unbounded(&DataType::Float64)?
296 )?])
297 .is_err()
298 );
299
300 assert!(
302 expr.evaluate_statistics(&[&Distribution::new_exponential(
303 ScalarValue::from(1.0),
304 ScalarValue::from(1.0),
305 true
306 )?])
307 .is_err()
308 );
309
310 assert!(
312 expr.evaluate_statistics(&[&Distribution::new_gaussian(
313 ScalarValue::from(1.0),
314 ScalarValue::from(1.0),
315 )?])
316 .is_err()
317 );
318
319 assert_eq!(
321 expr.evaluate_statistics(&[&Distribution::new_bernoulli(
322 ScalarValue::from(0.0),
323 )?])?,
324 Distribution::new_bernoulli(ScalarValue::from(1.))?
325 );
326
327 assert_eq!(
328 expr.evaluate_statistics(&[&Distribution::new_bernoulli(
329 ScalarValue::from(1.0),
330 )?])?,
331 Distribution::new_bernoulli(ScalarValue::from(0.))?
332 );
333
334 assert_eq!(
335 expr.evaluate_statistics(&[&Distribution::new_bernoulli(
336 ScalarValue::from(0.25),
337 )?])?,
338 Distribution::new_bernoulli(ScalarValue::from(0.75))?
339 );
340
341 assert!(
342 expr.evaluate_statistics(&[&Distribution::new_generic(
343 ScalarValue::Null,
344 ScalarValue::Null,
345 ScalarValue::Null,
346 Interval::make_unbounded(&DataType::UInt8)?
347 )?])
348 .is_err()
349 );
350
351 assert!(
353 expr.evaluate_statistics(&[&Distribution::new_generic(
354 ScalarValue::Null,
355 ScalarValue::Null,
356 ScalarValue::Null,
357 Interval::make_unbounded(&DataType::Float64)?
358 )?])
359 .is_err()
360 );
361
362 Ok(())
363 }
364
365 #[test]
366 fn test_fmt_sql() -> Result<()> {
367 let schema = schema();
368
369 let expr = not(col("a", &schema)?)?;
370
371 let display_string = expr.to_string();
372 assert_eq!(display_string, "NOT a@0");
373
374 let sql_string = fmt_sql(expr.as_ref()).to_string();
375 assert_eq!(sql_string, "NOT a");
376
377 Ok(())
378 }
379
380 fn schema() -> SchemaRef {
381 static SCHEMA: LazyLock<SchemaRef> = LazyLock::new(|| {
382 Arc::new(Schema::new(vec![Field::new("a", DataType::Boolean, true)]))
383 });
384 Arc::clone(&SCHEMA)
385 }
386}
387
388#[cfg(all(test, feature = "proto"))]
390mod proto_tests {
391 use super::*;
392 use crate::expressions::{Column, col};
393 use crate::proto_test_util::{
394 StubDecoder, StubEncoder, UnreachableDecoder, column_node,
395 };
396 use arrow::datatypes::Field;
397 use datafusion_common::DataFusionError;
398 use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
399 use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
400 use datafusion_proto_models::protobuf::{
401 PhysicalExprNode, PhysicalNot, physical_expr_node,
402 };
403
404 fn not_node(expr: Option<Box<PhysicalExprNode>>) -> PhysicalExprNode {
406 PhysicalExprNode {
407 expr_id: None,
408 expr_type: Some(physical_expr_node::ExprType::NotExpr(Box::new(
409 PhysicalNot { expr },
410 ))),
411 }
412 }
413
414 fn not_fixture() -> NotExpr {
416 let schema = Schema::new(vec![Field::new("a", DataType::Boolean, true)]);
417 NotExpr::new(col("a", &schema).unwrap())
418 }
419
420 #[test]
421 fn try_to_proto_encodes_not_expr() {
422 let not = not_fixture();
423 let encoder = StubEncoder::ok();
424 let ctx = PhysicalExprEncodeCtx::new(&encoder);
425
426 let node = not
427 .try_to_proto(&ctx)
428 .unwrap()
429 .expect("NotExpr should encode to Some(node)");
430
431 assert!(node.expr_id.is_none());
432 let not_node = match node.expr_type {
433 Some(physical_expr_node::ExprType::NotExpr(boxed)) => *boxed,
434 other => panic!("expected a NotExpr node, got {other:?}"),
435 };
436 assert!(not_node.expr.is_some());
437 }
438
439 #[test]
440 fn try_to_proto_propagates_expr_encode_error() {
441 let not = not_fixture();
442 let encoder = StubEncoder::failing_on(1);
443 let ctx = PhysicalExprEncodeCtx::new(&encoder);
444 let err = not.try_to_proto(&ctx).unwrap_err();
445 assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
446 }
447
448 #[test]
449 fn try_from_proto_decodes_not_expr() {
450 let node = not_node(Some(Box::new(column_node("a"))));
451 let schema = Schema::empty();
452 let decoder = StubDecoder::ok();
453 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
454
455 let decoded = NotExpr::try_from_proto(&node, &ctx).unwrap();
456 let not = decoded
457 .downcast_ref::<NotExpr>()
458 .expect("decoded expr should be a NotExpr");
459 assert!(not.arg().downcast_ref::<Column>().is_some());
460 }
461
462 #[test]
463 fn try_from_proto_rejects_non_not_node() {
464 let node = column_node("a");
465 let schema = Schema::empty();
466 let decoder = UnreachableDecoder;
467 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
468 let err = NotExpr::try_from_proto(&node, &ctx).unwrap_err();
469 assert!(
470 matches!(err, DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a NotExpr"))
471 );
472 }
473
474 #[test]
475 fn try_from_proto_rejects_missing_expr() {
476 let node = not_node(None);
477 let schema = Schema::empty();
478 let decoder = UnreachableDecoder;
479 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
480 let err = NotExpr::try_from_proto(&node, &ctx).unwrap_err();
481 assert!(
482 matches!(err, DataFusionError::Internal(msg) if msg.contains("NotExpr is missing required field 'expr'"))
483 );
484 }
485
486 #[test]
487 fn try_from_proto_propagates_expr_decode_error() {
488 let node = not_node(Some(Box::new(column_node("a"))));
489 let schema = Schema::empty();
490 let decoder = StubDecoder::failing_on(1);
491 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
492 let err = NotExpr::try_from_proto(&node, &ctx).unwrap_err();
493 assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
494 }
495}