Skip to main content

datafusion_physical_expr/expressions/
literal.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//! Literal expressions for physical operations
6
7use std::hash::Hash;
8use std::sync::Arc;
9
10use crate::physical_expr::PhysicalExpr;
11
12use arrow::datatypes::{Field, FieldRef};
13use arrow::{
14    datatypes::{DataType, Schema},
15    record_batch::RecordBatch,
16};
17use datafusion_common::metadata::FieldMetadata;
18use datafusion_common::{Result, ScalarValue};
19use datafusion_expr::Expr;
20use datafusion_expr_common::columnar_value::ColumnarValue;
21use datafusion_expr_common::interval_arithmetic::Interval;
22use datafusion_expr_common::placement::ExpressionPlacement;
23use datafusion_expr_common::sort_properties::{ExprProperties, SortProperties};
24
25/// Represents a literal value
26#[derive(Debug, PartialEq, Eq, Clone)]
27pub struct Literal {
28    value: ScalarValue,
29    field: FieldRef,
30}
31
32impl Hash for Literal {
33    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
34        self.value.hash(state);
35        let metadata = self.field.metadata();
36        let mut keys = metadata.keys().collect::<Vec<_>>();
37        keys.sort();
38        for key in keys {
39            key.hash(state);
40            metadata.get(key).unwrap().hash(state);
41        }
42    }
43}
44
45impl Literal {
46    /// Create a literal value expression
47    pub fn new(value: ScalarValue) -> Self {
48        Self::new_with_metadata(value, None)
49    }
50
51    /// Create a literal value expression
52    pub fn new_with_metadata(
53        value: ScalarValue,
54        metadata: Option<FieldMetadata>,
55    ) -> Self {
56        let mut field = Field::new("lit".to_string(), value.data_type(), value.is_null());
57
58        if let Some(metadata) = metadata {
59            field = metadata.add_to_field(field);
60        }
61
62        Self {
63            value,
64            field: field.into(),
65        }
66    }
67
68    /// Get the scalar value
69    pub fn value(&self) -> &ScalarValue {
70        &self.value
71    }
72}
73
74impl std::fmt::Display for Literal {
75    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
76        write!(f, "{}", self.value)
77    }
78}
79
80impl PhysicalExpr for Literal {
81    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
82        Ok(self.value.data_type())
83    }
84
85    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
86        Ok(self.value.is_null())
87    }
88
89    fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> {
90        Ok(Arc::clone(&self.field))
91    }
92
93    fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
94        Ok(ColumnarValue::Scalar(self.value.clone()))
95    }
96
97    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
98        vec![]
99    }
100
101    fn with_new_children(
102        self: Arc<Self>,
103        _children: Vec<Arc<dyn PhysicalExpr>>,
104    ) -> Result<Arc<dyn PhysicalExpr>> {
105        Ok(self)
106    }
107
108    fn get_properties(&self, _children: &[ExprProperties]) -> Result<ExprProperties> {
109        Ok(ExprProperties {
110            sort_properties: SortProperties::Singleton,
111            range: Interval::try_new(self.value().clone(), self.value().clone())?,
112            preserves_lex_ordering: true,
113            // Vacuously true: a literal has no ordered inputs.
114            strictly_order_preserving: true,
115        })
116    }
117
118    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        std::fmt::Display::fmt(self, f)
120    }
121
122    fn placement(&self) -> ExpressionPlacement {
123        ExpressionPlacement::Literal
124    }
125
126    #[cfg(feature = "proto")]
127    fn try_to_proto(
128        &self,
129        _ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
130    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
131        use datafusion_proto_models::protobuf;
132
133        let Self { value, field } = self;
134        // The field name, type, and nullability are reconstructed by new_with_metadata.
135        let expr_type = if field.metadata().is_empty() {
136            protobuf::physical_expr_node::ExprType::Literal(value.try_into()?)
137        } else {
138            protobuf::physical_expr_node::ExprType::LiteralWithMetadata(
139                protobuf::PhysicalLiteralNode {
140                    value: Some(value.try_into()?),
141                    metadata: field.metadata().into(),
142                },
143            )
144        };
145        Ok(Some(protobuf::PhysicalExprNode {
146            expr_id: None,
147            expr_type: Some(expr_type),
148        }))
149    }
150}
151
152#[cfg(feature = "proto")]
153impl Literal {
154    /// Reconstruct a [`Literal`] from its protobuf representation.
155    pub fn try_from_proto(
156        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
157        _ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
158    ) -> Result<Arc<dyn PhysicalExpr>> {
159        use datafusion_common::{internal_datafusion_err, internal_err};
160        use datafusion_proto_models::protobuf;
161        use protobuf::physical_expr_node::ExprType;
162
163        let protobuf::PhysicalExprNode {
164            expr_type,
165            // Expression IDs are handled by the enclosing proto converter.
166            expr_id: _,
167        } = node;
168        let (value, metadata) = match expr_type {
169            Some(ExprType::Literal(scalar)) => {
170                let datafusion_proto_models::datafusion_common::ScalarValue {
171                    // The scalar payload is decoded by ScalarValue::try_from.
172                    value: _,
173                } = scalar;
174                (ScalarValue::try_from(scalar)?, None)
175            }
176            Some(ExprType::LiteralWithMetadata(protobuf::PhysicalLiteralNode {
177                value,
178                metadata,
179            })) => {
180                let value = value.as_ref().ok_or_else(|| {
181                    internal_datafusion_err!("Literal is missing required field 'value'")
182                })?;
183                (
184                    ScalarValue::try_from(value)?,
185                    Some(FieldMetadata::from(metadata)),
186                )
187            }
188            _ => return internal_err!("PhysicalExprNode is not a Literal"),
189        };
190        Ok(Arc::new(Literal::new_with_metadata(value, metadata)))
191    }
192}
193
194/// Create a literal expression
195#[expect(clippy::needless_pass_by_value)]
196pub fn lit<T: datafusion_expr::Literal>(value: T) -> Arc<dyn PhysicalExpr> {
197    match value.lit() {
198        Expr::Literal(v, _) => Arc::new(Literal::new(v)),
199        _ => unreachable!(),
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    use arrow::array::Int32Array;
208    use datafusion_common::cast::as_int32_array;
209    use datafusion_physical_expr_common::physical_expr::fmt_sql;
210
211    #[test]
212    fn literal_i32() -> Result<()> {
213        // create an arbitrary record batch
214        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
215        let a = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5)]);
216        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;
217
218        // create and evaluate a literal expression
219        let literal_expr = lit(42i32);
220        assert_eq!("42", format!("{literal_expr}"));
221
222        let literal_array = literal_expr
223            .evaluate(&batch)?
224            .into_array(batch.num_rows())
225            .expect("Failed to convert to array");
226        let literal_array = as_int32_array(&literal_array)?;
227
228        // note that the contents of the literal array are unrelated to the batch contents except for the length of the array
229        assert_eq!(literal_array.len(), 5); // 5 rows in the batch
230        for i in 0..literal_array.len() {
231            assert_eq!(literal_array.value(i), 42);
232        }
233
234        Ok(())
235    }
236
237    #[test]
238    fn test_fmt_sql() -> Result<()> {
239        // create and evaluate a literal expression
240        let expr = lit(42i32);
241        let display_string = expr.to_string();
242        assert_eq!(display_string, "42");
243        let sql_string = fmt_sql(expr.as_ref()).to_string();
244        assert_eq!(sql_string, "42");
245
246        Ok(())
247    }
248}
249
250/// Tests for the `try_to_proto` / `try_from_proto` hooks.
251#[cfg(all(test, feature = "proto"))]
252mod proto_tests {
253    use super::*;
254    use crate::proto_test_util::{StubEncoder, UnreachableDecoder, column_node};
255    use datafusion_common::DataFusionError;
256    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
257    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
258    use datafusion_proto_models::protobuf::physical_expr_node;
259
260    fn i32_literal() -> Literal {
261        Literal::new(ScalarValue::Int32(Some(42)))
262    }
263
264    // ── try_to_proto ─────────────────────────────────────────────────────────
265
266    #[test]
267    fn try_to_proto_encodes_literal() {
268        let literal = i32_literal();
269        let encoder = StubEncoder::ok();
270        let ctx = PhysicalExprEncodeCtx::new(&encoder);
271
272        let node = literal
273            .try_to_proto(&ctx)
274            .unwrap()
275            .expect("Literal should encode to Some(node)");
276
277        // Literal nodes never set expr_id.
278        assert!(node.expr_id.is_none());
279        // Variant must be Literal, not any other expr type.
280        assert!(matches!(
281            node.expr_type,
282            Some(physical_expr_node::ExprType::Literal(_))
283        ));
284    }
285
286    #[test]
287    fn try_to_proto_null_literal() {
288        let literal = Literal::new(ScalarValue::Int32(None));
289        let encoder = StubEncoder::ok();
290        let ctx = PhysicalExprEncodeCtx::new(&encoder);
291
292        let node = literal
293            .try_to_proto(&ctx)
294            .unwrap()
295            .expect("null Literal should encode to Some(node)");
296
297        assert!(matches!(
298            node.expr_type,
299            Some(physical_expr_node::ExprType::Literal(_))
300        ));
301
302        // Decode and verify the null payload round-trips correctly.
303        let schema = Schema::empty();
304        let decoder = UnreachableDecoder;
305        let dec_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
306        let decoded = Literal::try_from_proto(&node, &dec_ctx).unwrap();
307        let lit = decoded
308            .downcast_ref::<Literal>()
309            .expect("decoded expr should be a Literal");
310        assert_eq!(lit.value(), &ScalarValue::Int32(None));
311    }
312
313    // ── try_from_proto ───────────────────────────────────────────────────────
314
315    #[test]
316    fn try_from_proto_roundtrip() {
317        let original = i32_literal();
318        let encoder = StubEncoder::ok();
319        let enc_ctx = PhysicalExprEncodeCtx::new(&encoder);
320
321        let node = original
322            .try_to_proto(&enc_ctx)
323            .unwrap()
324            .expect("should encode");
325
326        let schema = Schema::empty();
327        let decoder = UnreachableDecoder;
328        let dec_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
329
330        let decoded = Literal::try_from_proto(&node, &dec_ctx).unwrap();
331        let lit = decoded
332            .downcast_ref::<Literal>()
333            .expect("decoded expr should be a Literal");
334        assert_eq!(lit.value(), &ScalarValue::Int32(Some(42)));
335    }
336
337    #[test]
338    fn try_from_proto_rejects_missing_value() {
339        let node = datafusion_proto_models::protobuf::PhysicalExprNode {
340            expr_id: None,
341            expr_type: Some(physical_expr_node::ExprType::LiteralWithMetadata(
342                datafusion_proto_models::protobuf::PhysicalLiteralNode {
343                    value: None,
344                    metadata: Default::default(),
345                },
346            )),
347        };
348        let schema = Schema::empty();
349        let decoder = UnreachableDecoder;
350        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
351        let err = Literal::try_from_proto(&node, &ctx).unwrap_err();
352        assert!(
353            matches!(err, DataFusionError::Internal(msg) if msg.contains("Literal is missing required field 'value'"))
354        );
355    }
356
357    #[test]
358    fn try_from_proto_rejects_non_literal_node() {
359        let node = column_node("a");
360        let schema = Schema::empty();
361        let decoder = UnreachableDecoder;
362        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
363        let err = Literal::try_from_proto(&node, &ctx).unwrap_err();
364        assert!(
365            matches!(err, DataFusionError::Internal(ref msg) if msg.contains("PhysicalExprNode is not a Literal"))
366        );
367    }
368}