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    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        std::fmt::Display::fmt(self, f)
99    }
100}
101
102/// Create a literal expression
103pub fn lit<T: datafusion_expr::Literal>(value: T) -> Arc<dyn PhysicalExpr> {
104    match value.lit() {
105        Expr::Literal(v) => Arc::new(Literal::new(v)),
106        _ => unreachable!(),
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    use arrow::array::Int32Array;
115    use arrow::datatypes::*;
116    use datafusion_common::cast::as_int32_array;
117    use datafusion_physical_expr_common::physical_expr::fmt_sql;
118
119    #[test]
120    fn literal_i32() -> Result<()> {
121        // create an arbitrary record batch
122        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
123        let a = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5)]);
124        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;
125
126        // create and evaluate a literal expression
127        let literal_expr = lit(42i32);
128        assert_eq!("42", format!("{literal_expr}"));
129
130        let literal_array = literal_expr
131            .evaluate(&batch)?
132            .into_array(batch.num_rows())
133            .expect("Failed to convert to array");
134        let literal_array = as_int32_array(&literal_array)?;
135
136        // note that the contents of the literal array are unrelated to the batch contents except for the length of the array
137        assert_eq!(literal_array.len(), 5); // 5 rows in the batch
138        for i in 0..literal_array.len() {
139            assert_eq!(literal_array.value(i), 42);
140        }
141
142        Ok(())
143    }
144
145    #[test]
146    fn test_fmt_sql() -> Result<()> {
147        // create and evaluate a literal expression
148        let expr = lit(42i32);
149        let display_string = expr.to_string();
150        assert_eq!(display_string, "42");
151        let sql_string = fmt_sql(expr.as_ref()).to_string();
152        assert_eq!(sql_string, "42");
153
154        Ok(())
155    }
156}