datafusion_physical_expr/expressions/
literal.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Literal expressions for physical operations
19
20use std::any::Any;
21use std::hash::Hash;
22use std::sync::Arc;
23
24use crate::physical_expr::PhysicalExpr;
25
26use arrow::{
27    datatypes::{DataType, Schema},
28    record_batch::RecordBatch,
29};
30use datafusion_common::{Result, ScalarValue};
31use datafusion_expr::Expr;
32use datafusion_expr_common::columnar_value::ColumnarValue;
33use datafusion_expr_common::interval_arithmetic::Interval;
34use datafusion_expr_common::sort_properties::{ExprProperties, SortProperties};
35
36/// Represents a literal value
37#[derive(Debug, PartialEq, Eq, Hash)]
38pub struct Literal {
39    value: ScalarValue,
40}
41
42impl Literal {
43    /// Create a literal value expression
44    pub fn new(value: ScalarValue) -> Self {
45        Self { value }
46    }
47
48    /// Get the scalar value
49    pub fn value(&self) -> &ScalarValue {
50        &self.value
51    }
52}
53
54impl std::fmt::Display for Literal {
55    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
56        write!(f, "{}", self.value)
57    }
58}
59
60impl PhysicalExpr for Literal {
61    /// Return a reference to Any that can be used for downcasting
62    fn as_any(&self) -> &dyn Any {
63        self
64    }
65
66    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
67        Ok(self.value.data_type())
68    }
69
70    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
71        Ok(self.value.is_null())
72    }
73
74    fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
75        Ok(ColumnarValue::Scalar(self.value.clone()))
76    }
77
78    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
79        vec![]
80    }
81
82    fn with_new_children(
83        self: Arc<Self>,
84        _children: Vec<Arc<dyn PhysicalExpr>>,
85    ) -> Result<Arc<dyn PhysicalExpr>> {
86        Ok(self)
87    }
88
89    fn get_properties(&self, _children: &[ExprProperties]) -> Result<ExprProperties> {
90        Ok(ExprProperties {
91            sort_properties: SortProperties::Singleton,
92            range: Interval::try_new(self.value().clone(), self.value().clone())?,
93            preserves_lex_ordering: true,
94        })
95    }
96}
97
98/// Create a literal expression
99pub fn lit<T: datafusion_expr::Literal>(value: T) -> Arc<dyn PhysicalExpr> {
100    match value.lit() {
101        Expr::Literal(v) => Arc::new(Literal::new(v)),
102        _ => unreachable!(),
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    use arrow::array::Int32Array;
111    use arrow::datatypes::*;
112    use datafusion_common::cast::as_int32_array;
113
114    #[test]
115    fn literal_i32() -> Result<()> {
116        // create an arbitrary record batch
117        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
118        let a = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5)]);
119        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;
120
121        // create and evaluate a literal expression
122        let literal_expr = lit(42i32);
123        assert_eq!("42", format!("{literal_expr}"));
124
125        let literal_array = literal_expr
126            .evaluate(&batch)?
127            .into_array(batch.num_rows())
128            .expect("Failed to convert to array");
129        let literal_array = as_int32_array(&literal_array)?;
130
131        // note that the contents of the literal array are unrelated to the batch contents except for the length of the array
132        assert_eq!(literal_array.len(), 5); // 5 rows in the batch
133        for i in 0..literal_array.len() {
134            assert_eq!(literal_array.value(i), 42);
135        }
136
137        Ok(())
138    }
139}