Skip to main content

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::hash::Hash;
21use std::sync::Arc;
22
23use crate::physical_expr::PhysicalExpr;
24
25use arrow::datatypes::{Field, FieldRef};
26use arrow::{
27    datatypes::{DataType, Schema},
28    record_batch::RecordBatch,
29};
30use datafusion_common::metadata::FieldMetadata;
31use datafusion_common::{Result, ScalarValue};
32use datafusion_expr::Expr;
33use datafusion_expr_common::columnar_value::ColumnarValue;
34use datafusion_expr_common::interval_arithmetic::Interval;
35use datafusion_expr_common::placement::ExpressionPlacement;
36use datafusion_expr_common::sort_properties::{ExprProperties, SortProperties};
37
38/// Represents a literal value
39#[derive(Debug, PartialEq, Eq, Clone)]
40pub struct Literal {
41    value: ScalarValue,
42    field: FieldRef,
43}
44
45impl Hash for Literal {
46    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
47        self.value.hash(state);
48        let metadata = self.field.metadata();
49        let mut keys = metadata.keys().collect::<Vec<_>>();
50        keys.sort();
51        for key in keys {
52            key.hash(state);
53            metadata.get(key).unwrap().hash(state);
54        }
55    }
56}
57
58impl Literal {
59    /// Create a literal value expression
60    pub fn new(value: ScalarValue) -> Self {
61        Self::new_with_metadata(value, None)
62    }
63
64    /// Create a literal value expression
65    pub fn new_with_metadata(
66        value: ScalarValue,
67        metadata: Option<FieldMetadata>,
68    ) -> Self {
69        let mut field = Field::new("lit".to_string(), value.data_type(), value.is_null());
70
71        if let Some(metadata) = metadata {
72            field = metadata.add_to_field(field);
73        }
74
75        Self {
76            value,
77            field: field.into(),
78        }
79    }
80
81    /// Get the scalar value
82    pub fn value(&self) -> &ScalarValue {
83        &self.value
84    }
85}
86
87impl std::fmt::Display for Literal {
88    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
89        write!(f, "{}", self.value)
90    }
91}
92
93impl PhysicalExpr for Literal {
94    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
95        Ok(self.value.data_type())
96    }
97
98    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
99        Ok(self.value.is_null())
100    }
101
102    fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> {
103        Ok(Arc::clone(&self.field))
104    }
105
106    fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
107        Ok(ColumnarValue::Scalar(self.value.clone()))
108    }
109
110    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
111        vec![]
112    }
113
114    fn with_new_children(
115        self: Arc<Self>,
116        _children: Vec<Arc<dyn PhysicalExpr>>,
117    ) -> Result<Arc<dyn PhysicalExpr>> {
118        Ok(self)
119    }
120
121    fn get_properties(&self, _children: &[ExprProperties]) -> Result<ExprProperties> {
122        Ok(ExprProperties {
123            sort_properties: SortProperties::Singleton,
124            range: Interval::try_new(self.value().clone(), self.value().clone())?,
125            preserves_lex_ordering: true,
126        })
127    }
128
129    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        std::fmt::Display::fmt(self, f)
131    }
132
133    fn placement(&self) -> ExpressionPlacement {
134        ExpressionPlacement::Literal
135    }
136}
137
138/// Create a literal expression
139#[expect(clippy::needless_pass_by_value)]
140pub fn lit<T: datafusion_expr::Literal>(value: T) -> Arc<dyn PhysicalExpr> {
141    match value.lit() {
142        Expr::Literal(v, _) => Arc::new(Literal::new(v)),
143        _ => unreachable!(),
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    use arrow::array::Int32Array;
152    use datafusion_common::cast::as_int32_array;
153    use datafusion_physical_expr_common::physical_expr::fmt_sql;
154
155    #[test]
156    fn literal_i32() -> Result<()> {
157        // create an arbitrary record batch
158        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
159        let a = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5)]);
160        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;
161
162        // create and evaluate a literal expression
163        let literal_expr = lit(42i32);
164        assert_eq!("42", format!("{literal_expr}"));
165
166        let literal_array = literal_expr
167            .evaluate(&batch)?
168            .into_array(batch.num_rows())
169            .expect("Failed to convert to array");
170        let literal_array = as_int32_array(&literal_array)?;
171
172        // note that the contents of the literal array are unrelated to the batch contents except for the length of the array
173        assert_eq!(literal_array.len(), 5); // 5 rows in the batch
174        for i in 0..literal_array.len() {
175            assert_eq!(literal_array.value(i), 42);
176        }
177
178        Ok(())
179    }
180
181    #[test]
182    fn test_fmt_sql() -> Result<()> {
183        // create and evaluate a literal expression
184        let expr = lit(42i32);
185        let display_string = expr.to_string();
186        assert_eq!(display_string, "42");
187        let sql_string = fmt_sql(expr.as_ref()).to_string();
188        assert_eq!(sql_string, "42");
189
190        Ok(())
191    }
192}