datafusion_physical_expr/expressions/
literal.rs1use 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#[derive(Debug, PartialEq, Eq, Hash)]
38pub struct Literal {
39 value: ScalarValue,
40}
41
42impl Literal {
43 pub fn new(value: ScalarValue) -> Self {
45 Self { value }
46 }
47
48 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 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
98pub 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 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 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 assert_eq!(literal_array.len(), 5); for i in 0..literal_array.len() {
134 assert_eq!(literal_array.value(i), 42);
135 }
136
137 Ok(())
138 }
139}