Skip to main content

datafusion_physical_expr/expressions/
negative.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//! Negation (-) expression
6
7use std::hash::Hash;
8use std::sync::Arc;
9
10use crate::PhysicalExpr;
11
12use arrow::datatypes::FieldRef;
13use arrow::{
14    compute::kernels::numeric::neg_wrapping,
15    datatypes::{DataType, Schema},
16    record_batch::RecordBatch,
17};
18use datafusion_common::{Result, ScalarValue, internal_err, plan_err};
19use datafusion_expr::interval_arithmetic::Interval;
20use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
21#[expect(deprecated)]
22use datafusion_expr::statistics::Distribution::{
23    self, Bernoulli, Exponential, Gaussian, Generic, Uniform,
24};
25use datafusion_expr::{
26    ColumnarValue,
27    type_coercion::{is_interval, is_signed_numeric, is_timestamp},
28};
29
30/// Negative expression
31#[derive(Debug, Eq)]
32pub struct NegativeExpr {
33    /// Input expression
34    arg: Arc<dyn PhysicalExpr>,
35}
36
37// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
38impl PartialEq for NegativeExpr {
39    fn eq(&self, other: &Self) -> bool {
40        self.arg.eq(&other.arg)
41    }
42}
43
44impl Hash for NegativeExpr {
45    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
46        self.arg.hash(state);
47    }
48}
49
50impl NegativeExpr {
51    /// Create new not expression
52    pub fn new(arg: Arc<dyn PhysicalExpr>) -> Self {
53        Self { arg }
54    }
55
56    /// Get the input expression
57    pub fn arg(&self) -> &Arc<dyn PhysicalExpr> {
58        &self.arg
59    }
60}
61
62impl std::fmt::Display for NegativeExpr {
63    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
64        write!(f, "(- {})", self.arg)
65    }
66}
67
68impl PhysicalExpr for NegativeExpr {
69    fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
70        self.arg.data_type(input_schema)
71    }
72
73    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
74        self.arg.nullable(input_schema)
75    }
76
77    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
78        match self.arg.evaluate(batch)? {
79            ColumnarValue::Array(array) => {
80                let result = neg_wrapping(array.as_ref())?;
81                Ok(ColumnarValue::Array(result))
82            }
83            ColumnarValue::Scalar(scalar) => {
84                Ok(ColumnarValue::Scalar(scalar.arithmetic_negate()?))
85            }
86        }
87    }
88
89    fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> {
90        self.arg.return_field(input_schema)
91    }
92
93    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
94        vec![&self.arg]
95    }
96
97    fn with_new_children(
98        self: Arc<Self>,
99        children: Vec<Arc<dyn PhysicalExpr>>,
100    ) -> Result<Arc<dyn PhysicalExpr>> {
101        Ok(Arc::new(NegativeExpr::new(Arc::clone(&children[0]))))
102    }
103
104    /// Given the child interval of a NegativeExpr, it calculates the NegativeExpr's interval.
105    /// Reflects the bounds unless signed integer negation can wrap.
106    fn evaluate_bounds(&self, children: &[&Interval]) -> Result<Interval> {
107        negate_bounds(children[0])
108    }
109
110    /// Returns a new [`Interval`] of a NegativeExpr  that has the existing `interval` given that
111    /// given the input interval is known to be `children`.
112    fn propagate_constraints(
113        &self,
114        interval: &Interval,
115        children: &[&Interval],
116    ) -> Result<Option<Vec<Interval>>> {
117        let negated_interval = negate_bounds(interval)?;
118
119        Ok(children[0]
120            .intersect(negated_interval)?
121            .map(|result| vec![result]))
122    }
123
124    #[expect(deprecated)]
125    fn evaluate_statistics(&self, children: &[&Distribution]) -> Result<Distribution> {
126        match children[0] {
127            Uniform(u) => Distribution::new_uniform(u.range().arithmetic_negate()?),
128            Exponential(e) => Distribution::new_exponential(
129                e.rate().clone(),
130                e.offset().arithmetic_negate()?,
131                !e.positive_tail(),
132            ),
133            Gaussian(g) => Distribution::new_gaussian(
134                g.mean().arithmetic_negate()?,
135                g.variance().clone(),
136            ),
137            Bernoulli(_) => {
138                internal_err!("NegativeExpr cannot operate on Boolean datatypes")
139            }
140            Generic(u) => Distribution::new_generic(
141                u.mean().arithmetic_negate()?,
142                u.median().arithmetic_negate()?,
143                u.variance().clone(),
144                u.range().arithmetic_negate()?,
145            ),
146        }
147    }
148
149    /// Negation reverses ordering only when the input cannot cross a wrap.
150    fn get_properties(&self, children: &[ExprProperties]) -> Result<ExprProperties> {
151        Ok(ExprProperties {
152            sort_properties: if children[0].sort_properties != SortProperties::Singleton
153                && negation_may_wrap(&children[0].range)
154            {
155                SortProperties::Unordered
156            } else {
157                -children[0].sort_properties
158            },
159            range: negate_bounds(&children[0].range)?,
160            preserves_lex_ordering: false,
161            // Negation is one-to-one but reverses the ordering direction.
162            strictly_order_preserving: false,
163        })
164    }
165
166    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        write!(f, "(- ")?;
168        self.arg.fmt_sql(f)?;
169        write!(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::Negative(Box::new(
183                protobuf::PhysicalNegativeNode {
184                    expr: Some(Box::new(ctx.encode_child(arg)?)),
185                },
186            ))),
187        }))
188    }
189}
190
191fn negate_bounds(range: &Interval) -> Result<Interval> {
192    if range.data_type() == DataType::Null {
193        return Ok(range.clone());
194    }
195    if range.data_type().is_signed_integer() && negation_may_wrap(range) {
196        // Do not derive bounds across a possible integer wrap.
197        return Interval::make_unbounded(&range.data_type());
198    }
199    range.arithmetic_negate()
200}
201
202// Signed integer array negation wraps at the minimum value.
203fn negation_may_wrap(range: &Interval) -> bool {
204    let data_type = range.data_type();
205    data_type == DataType::Null
206        || (data_type.is_signed_integer()
207            && (range.lower().is_null()
208                || ScalarValue::min(&data_type).as_ref() == Some(range.lower())))
209}
210
211#[cfg(feature = "proto")]
212impl NegativeExpr {
213    /// Reconstruct a [`NegativeExpr`] from its protobuf representation.
214    pub fn try_from_proto(
215        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
216        ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
217    ) -> Result<Arc<dyn PhysicalExpr>> {
218        use datafusion_physical_expr_common::expect_expr_variant;
219        use datafusion_proto_models::protobuf;
220
221        let n = expect_expr_variant!(
222            node,
223            protobuf::physical_expr_node::ExprType::Negative,
224            "Negative",
225        );
226        let protobuf::PhysicalNegativeNode { expr } = n.as_ref();
227        let expr =
228            ctx.decode_required_expression(expr.as_deref(), "NegativeExpr", "expr")?;
229
230        Ok(Arc::new(NegativeExpr::new(expr)))
231    }
232}
233
234/// Creates a unary expression NEGATIVE
235///
236/// # Errors
237///
238/// This function errors when the argument's type is not signed numeric
239pub fn negative(
240    arg: Arc<dyn PhysicalExpr>,
241    input_schema: &Schema,
242) -> Result<Arc<dyn PhysicalExpr>> {
243    let data_type = arg.data_type(input_schema)?;
244    if data_type.is_null() {
245        Ok(arg)
246    } else if !is_signed_numeric(&data_type)
247        && !is_interval(&data_type)
248        && !is_timestamp(&data_type)
249    {
250        plan_err!("Negation only supports numeric, interval and timestamp types")
251    } else {
252        Ok(Arc::new(NegativeExpr::new(arg)))
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use crate::expressions::{Column, col};
260
261    use arrow::array::*;
262    use arrow::datatypes::DataType::{Float32, Float64, Int8, Int16, Int32, Int64};
263    use arrow::datatypes::*;
264    use datafusion_common::cast::as_primitive_array;
265    use datafusion_common::{DataFusionError, ScalarValue};
266
267    use datafusion_physical_expr_common::physical_expr::fmt_sql;
268
269    macro_rules! test_array_negative_op {
270        ($DATA_TY:tt, $ARRAY_TY:ty, $($VALUE:expr),*   ) => {
271            let schema = Schema::new(vec![Field::new("a", DataType::$DATA_TY, true)]);
272            let expr = negative(col("a", &schema)?, &schema)?;
273            assert_eq!(expr.data_type(&schema)?, DataType::$DATA_TY);
274            assert!(expr.nullable(&schema)?);
275            let mut arr = Vec::new();
276            let mut arr_expected = Vec::new();
277            $(
278                arr.push(Some($VALUE));
279                arr_expected.push(Some(-$VALUE));
280            )+
281            arr.push(None);
282            arr_expected.push(None);
283            let input = <$ARRAY_TY>::from(arr);
284            let expected = &<$ARRAY_TY>::from(arr_expected);
285            let batch =
286                RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(input)])?;
287            let result = expr.evaluate(&batch)?.into_array(batch.num_rows()).expect("Failed to convert to array");
288            let result =
289                as_primitive_array(&result).expect(format!("failed to downcast to {:?}Array", $DATA_TY).as_str());
290            assert_eq!(result, expected);
291        };
292    }
293
294    #[test]
295    fn array_negative_op() -> Result<()> {
296        test_array_negative_op!(Int8, Int8Array, 2i8, 1i8);
297        test_array_negative_op!(Int16, Int16Array, 234i16, 123i16);
298        test_array_negative_op!(Int32, Int32Array, 2345i32, 1234i32);
299        test_array_negative_op!(Int64, Int64Array, 23456i64, 12345i64);
300        test_array_negative_op!(Float32, Float32Array, 2345.0f32, 1234.0f32);
301        test_array_negative_op!(Float64, Float64Array, 23456.0f64, 12345.0f64);
302        Ok(())
303    }
304
305    #[test]
306    fn test_wrapping_negation_properties() {
307        let expr = NegativeExpr::new(Arc::new(Column::new("a", 0)));
308        let ordered = SortProperties::Ordered(Default::default());
309        for data_type in [Int8, Int16, Int32, Int64] {
310            let minimum = ScalarValue::min(&data_type).unwrap();
311            let full = Interval::make_unbounded(&data_type).unwrap();
312            let singleton = Interval::try_new(minimum.clone(), minimum.clone()).unwrap();
313            for range in [
314                full.clone(),
315                singleton.clone(),
316                Interval::try_new(ScalarValue::try_from(&data_type).unwrap(), minimum)
317                    .unwrap(),
318            ] {
319                let child = ExprProperties::new_unknown()
320                    .with_range(range.clone())
321                    .with_order(ordered);
322                let result = expr.get_properties(&[child]).unwrap();
323                assert_eq!(result.sort_properties, SortProperties::Unordered);
324                assert_eq!(result.range, full);
325                assert_eq!(expr.evaluate_bounds(&[&range]).unwrap(), full);
326                assert_eq!(
327                    expr.propagate_constraints(&range, &[&full]).unwrap(),
328                    Some(vec![full.clone()])
329                );
330            }
331            let child = ExprProperties::new_unknown()
332                .with_range(singleton)
333                .with_order(SortProperties::Singleton);
334            assert_eq!(
335                expr.get_properties(&[child]).unwrap().sort_properties,
336                SortProperties::Singleton
337            );
338        }
339    }
340
341    #[test]
342    fn test_non_wrapping_negation_properties() {
343        let expr = NegativeExpr::new(Arc::new(Column::new("a", 0)));
344        let ranges = [
345            Interval::make(Some(i8::MIN + 1), Some(1_i8)).unwrap(),
346            Interval::make(Some(i16::MIN + 1), Some(1_i16)).unwrap(),
347            Interval::make(Some(i32::MIN + 1), Some(1_i32)).unwrap(),
348            Interval::make(Some(i64::MIN + 1), Some(1_i64)).unwrap(),
349            // An unbounded upper bound cannot introduce MIN when the lower bound excludes it.
350            Interval::make(Some(i8::MIN + 1), None).unwrap(),
351            Interval::make(Some(i16::MIN + 1), None).unwrap(),
352            Interval::make(Some(i32::MIN + 1), None).unwrap(),
353            Interval::make(Some(i64::MIN + 1), None).unwrap(),
354            Interval::make(Some(-2_f32), Some(1_f32)).unwrap(),
355            Interval::make(Some(-2_f64), Some(1_f64)).unwrap(),
356            Interval::make_unbounded(&Float32).unwrap(),
357            Interval::make_unbounded(&Float64).unwrap(),
358        ];
359        for range in ranges {
360            let expected_range = range.arithmetic_negate().unwrap();
361            for descending in [false, true] {
362                for nulls_first in [false, true] {
363                    let ordered = SortProperties::Ordered(arrow::compute::SortOptions {
364                        descending,
365                        nulls_first,
366                    });
367                    let child = ExprProperties::new_unknown()
368                        .with_range(range.clone())
369                        .with_order(ordered);
370                    let result = expr.get_properties(&[child]).unwrap();
371                    assert_eq!(result.sort_properties, -ordered);
372                    assert_eq!(result.range, expected_range);
373                }
374            }
375            assert_eq!(expr.evaluate_bounds(&[&range]).unwrap(), expected_range);
376            assert_eq!(
377                expr.propagate_constraints(&expected_range, &[&range])
378                    .unwrap(),
379                Some(vec![range])
380            );
381        }
382    }
383
384    #[test]
385    fn test_unknown_negation_properties() {
386        let expr = NegativeExpr::new(Arc::new(Column::new("a", 0)));
387        for order in [
388            SortProperties::Ordered(Default::default()),
389            SortProperties::Unordered,
390            SortProperties::Singleton,
391        ] {
392            let child = ExprProperties::new_unknown().with_order(order);
393            let range = child.range.clone();
394            let result = expr.get_properties(&[child]).unwrap();
395            assert_eq!(
396                result.sort_properties,
397                if order == SortProperties::Singleton {
398                    SortProperties::Singleton
399                } else {
400                    SortProperties::Unordered
401                }
402            );
403            assert_eq!(result.range, range);
404            assert_eq!(expr.evaluate_bounds(&[&range]).unwrap(), range);
405        }
406    }
407
408    #[test]
409    fn test_negation_bounds_errors() {
410        let expr = NegativeExpr::new(Arc::new(Column::new("a", 0)));
411        // Boolean intervals cannot be negated. All callers must propagate the error.
412        let range = Interval::make(Some(false), Some(true)).unwrap();
413        let child = ExprProperties::new_unknown().with_range(range.clone());
414        // Compare the error messages without call-site-dependent backtraces.
415        let expected = range.arithmetic_negate().unwrap_err().strip_backtrace();
416        assert_eq!(
417            expr.evaluate_bounds(&[&range])
418                .unwrap_err()
419                .strip_backtrace(),
420            expected
421        );
422        assert_eq!(
423            expr.get_properties(&[child]).unwrap_err().strip_backtrace(),
424            expected
425        );
426        assert_eq!(
427            expr.propagate_constraints(&range, &[&range])
428                .unwrap_err()
429                .strip_backtrace(),
430            expected
431        );
432    }
433
434    #[test]
435    fn test_evaluate_bounds() -> Result<()> {
436        let negative_expr = NegativeExpr::new(Arc::new(Column::new("a", 0)));
437        let child_interval = Interval::make(Some(-2), Some(1))?;
438        let negative_expr_interval = Interval::make(Some(-1), Some(2))?;
439        assert_eq!(
440            negative_expr.evaluate_bounds(&[&child_interval])?,
441            negative_expr_interval
442        );
443        Ok(())
444    }
445
446    #[test]
447    #[expect(deprecated)]
448    fn test_evaluate_statistics() -> Result<()> {
449        let negative_expr = NegativeExpr::new(Arc::new(Column::new("a", 0)));
450
451        // Uniform
452        assert_eq!(
453            negative_expr.evaluate_statistics(&[&Distribution::new_uniform(
454                Interval::make(Some(-2.), Some(3.))?
455            )?])?,
456            Distribution::new_uniform(Interval::make(Some(-3.), Some(2.))?)?
457        );
458
459        // Bernoulli
460        assert!(
461            negative_expr
462                .evaluate_statistics(&[&Distribution::new_bernoulli(ScalarValue::from(
463                    0.75
464                ))?])
465                .is_err()
466        );
467
468        // Exponential
469        assert_eq!(
470            negative_expr.evaluate_statistics(&[&Distribution::new_exponential(
471                ScalarValue::from(1.),
472                ScalarValue::from(1.),
473                true
474            )?])?,
475            Distribution::new_exponential(
476                ScalarValue::from(1.),
477                ScalarValue::from(-1.),
478                false
479            )?
480        );
481
482        // Gaussian
483        assert_eq!(
484            negative_expr.evaluate_statistics(&[&Distribution::new_gaussian(
485                ScalarValue::from(15),
486                ScalarValue::from(225),
487            )?])?,
488            Distribution::new_gaussian(ScalarValue::from(-15), ScalarValue::from(225),)?
489        );
490
491        // Unknown
492        assert_eq!(
493            negative_expr.evaluate_statistics(&[&Distribution::new_generic(
494                ScalarValue::from(15),
495                ScalarValue::from(15),
496                ScalarValue::from(10),
497                Interval::make(Some(10), Some(20))?
498            )?])?,
499            Distribution::new_generic(
500                ScalarValue::from(-15),
501                ScalarValue::from(-15),
502                ScalarValue::from(10),
503                Interval::make(Some(-20), Some(-10))?
504            )?
505        );
506
507        Ok(())
508    }
509
510    #[test]
511    fn test_propagate_constraints() -> Result<()> {
512        let negative_expr = NegativeExpr::new(Arc::new(Column::new("a", 0)));
513        let original_child_interval = Interval::make(Some(-2), Some(3))?;
514        let negative_expr_interval = Interval::make(Some(0), Some(4))?;
515        let after_propagation = Some(vec![Interval::make(Some(-2), Some(0))?]);
516        assert_eq!(
517            negative_expr.propagate_constraints(
518                &negative_expr_interval,
519                &[&original_child_interval]
520            )?,
521            after_propagation
522        );
523        Ok(())
524    }
525
526    #[test]
527    #[expect(deprecated)]
528    fn test_propagate_statistics_range_holders() -> Result<()> {
529        let negative_expr = NegativeExpr::new(Arc::new(Column::new("a", 0)));
530        let original_child_interval = Interval::make(Some(-2), Some(3))?;
531        let after_propagation = Interval::make(Some(-2), Some(0))?;
532
533        let parent = Distribution::new_uniform(Interval::make(Some(0), Some(4))?)?;
534        let children: Vec<Vec<Distribution>> = vec![
535            vec![Distribution::new_uniform(original_child_interval.clone())?],
536            vec![Distribution::new_generic(
537                ScalarValue::from(0),
538                ScalarValue::from(0),
539                ScalarValue::Int32(None),
540                original_child_interval.clone(),
541            )?],
542        ];
543
544        for child_view in children {
545            let child_refs: Vec<_> = child_view.iter().collect();
546            let actual = negative_expr.propagate_statistics(&parent, &child_refs)?;
547            let expected = Some(vec![Distribution::new_from_interval(
548                after_propagation.clone(),
549            )?]);
550            assert_eq!(actual, expected);
551        }
552
553        Ok(())
554    }
555
556    #[test]
557    fn test_negation_valid_types() -> Result<()> {
558        let negatable_types = [
559            Int8,
560            DataType::Timestamp(TimeUnit::Second, None),
561            DataType::Interval(IntervalUnit::YearMonth),
562        ];
563        for negatable_type in negatable_types {
564            let schema = Schema::new(vec![Field::new("a", negatable_type, true)]);
565            let _expr = negative(col("a", &schema)?, &schema)?;
566        }
567        Ok(())
568    }
569
570    #[test]
571    fn test_negation_invalid_types() -> Result<()> {
572        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
573        let expr = negative(col("a", &schema)?, &schema).unwrap_err();
574        matches!(expr, DataFusionError::Plan(_));
575        Ok(())
576    }
577
578    #[test]
579    fn test_fmt_sql() -> Result<()> {
580        let expr = NegativeExpr::new(Arc::new(Column::new("a", 0)));
581        let display_string = expr.to_string();
582        assert_eq!(display_string, "(- a@0)");
583        let sql_string = fmt_sql(&expr).to_string();
584        assert_eq!(sql_string, "(- a)");
585
586        Ok(())
587    }
588}
589
590#[cfg(all(test, feature = "proto"))]
591mod proto_tests {
592    use super::*;
593    use crate::expressions::{Column, col};
594    use crate::proto_test_util::{
595        StubDecoder, StubEncoder, UnreachableDecoder, column_node,
596    };
597    use arrow::datatypes::Field;
598    use datafusion_common::DataFusionError;
599    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
600    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
601    use datafusion_proto_models::protobuf::{
602        PhysicalExprNode, PhysicalNegativeNode, physical_expr_node,
603    };
604
605    /// Build a `NegativeExpr` proto node with the given children.
606    fn negative_node(expr: Option<Box<PhysicalExprNode>>) -> PhysicalExprNode {
607        PhysicalExprNode {
608            expr_id: None,
609            expr_type: Some(physical_expr_node::ExprType::Negative(Box::new(
610                PhysicalNegativeNode { expr },
611            ))),
612        }
613    }
614
615    /// A `NegativeExpr` over a column of type Int32.
616    fn negative_fixture() -> NegativeExpr {
617        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
618        NegativeExpr::new(col("a", &schema).unwrap())
619    }
620
621    #[test]
622    fn try_to_proto_encodes_negative_expr() {
623        let negative = negative_fixture();
624        let encoder = StubEncoder::ok();
625        let ctx = PhysicalExprEncodeCtx::new(&encoder);
626
627        let node = negative
628            .try_to_proto(&ctx)
629            .unwrap()
630            .expect("NegativeExpr should encode to Some(node)");
631
632        assert!(node.expr_id.is_none());
633        let negative_node = match node.expr_type {
634            Some(physical_expr_node::ExprType::Negative(boxed)) => *boxed,
635            other => panic!("expected a NegativeExpr node, got {other:?}"),
636        };
637        assert!(negative_node.expr.is_some());
638    }
639
640    #[test]
641    fn try_to_proto_propagates_expr_encode_error() {
642        let negative = negative_fixture();
643        let encoder = StubEncoder::failing_on(1);
644        let ctx = PhysicalExprEncodeCtx::new(&encoder);
645        let err = negative.try_to_proto(&ctx).unwrap_err();
646        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
647    }
648
649    #[test]
650    fn try_from_proto_decodes_negative_expr() {
651        let node = negative_node(Some(Box::new(column_node("a"))));
652        let schema = Schema::empty();
653        let decoder = StubDecoder::ok();
654        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
655
656        let decoded = NegativeExpr::try_from_proto(&node, &ctx).unwrap();
657        let negative = decoded
658            .downcast_ref::<NegativeExpr>()
659            .expect("decoded expr should be a NegativeExpr");
660        assert!(negative.arg().downcast_ref::<Column>().is_some());
661    }
662
663    #[test]
664    fn try_from_proto_rejects_non_negative_node() {
665        let node = column_node("a");
666        let schema = Schema::empty();
667        let decoder = UnreachableDecoder;
668        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
669        let err = NegativeExpr::try_from_proto(&node, &ctx).unwrap_err();
670        assert!(
671            matches!(err, DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a Negative"))
672        );
673    }
674
675    #[test]
676    fn try_from_proto_rejects_missing_expr() {
677        let node = negative_node(None);
678        let schema = Schema::empty();
679        let decoder = UnreachableDecoder;
680        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
681        let err = NegativeExpr::try_from_proto(&node, &ctx).unwrap_err();
682        assert!(
683            matches!(err, DataFusionError::Internal(msg) if msg.contains("NegativeExpr is missing required field 'expr'"))
684        );
685    }
686
687    #[test]
688    fn try_from_proto_propagates_expr_decode_error() {
689        let node = negative_node(Some(Box::new(column_node("a"))));
690        let schema = Schema::empty();
691        let decoder = StubDecoder::failing_on(1);
692        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
693        let err = NegativeExpr::try_from_proto(&node, &ctx).unwrap_err();
694        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
695    }
696}