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::datatypes::{Field, FieldRef};
27use arrow::{
28 datatypes::{DataType, Schema},
29 record_batch::RecordBatch,
30};
31use datafusion_common::{Result, ScalarValue};
32use datafusion_expr::expr::FieldMetadata;
33use datafusion_expr::Expr;
34use datafusion_expr_common::columnar_value::ColumnarValue;
35use datafusion_expr_common::interval_arithmetic::Interval;
36use datafusion_expr_common::sort_properties::{ExprProperties, SortProperties};
37
38#[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 pub fn new(value: ScalarValue) -> Self {
61 Self::new_with_metadata(value, None)
62 }
63
64 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 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 as_any(&self) -> &dyn Any {
96 self
97 }
98
99 fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
100 Ok(self.value.data_type())
101 }
102
103 fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
104 Ok(self.value.is_null())
105 }
106
107 fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> {
108 Ok(Arc::clone(&self.field))
109 }
110
111 fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
112 Ok(ColumnarValue::Scalar(self.value.clone()))
113 }
114
115 fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
116 vec![]
117 }
118
119 fn with_new_children(
120 self: Arc<Self>,
121 _children: Vec<Arc<dyn PhysicalExpr>>,
122 ) -> Result<Arc<dyn PhysicalExpr>> {
123 Ok(self)
124 }
125
126 fn get_properties(&self, _children: &[ExprProperties]) -> Result<ExprProperties> {
127 Ok(ExprProperties {
128 sort_properties: SortProperties::Singleton,
129 range: Interval::try_new(self.value().clone(), self.value().clone())?,
130 preserves_lex_ordering: true,
131 })
132 }
133
134 fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135 std::fmt::Display::fmt(self, f)
136 }
137}
138
139pub 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 arrow::datatypes::Field;
153 use datafusion_common::cast::as_int32_array;
154 use datafusion_physical_expr_common::physical_expr::fmt_sql;
155
156 #[test]
157 fn literal_i32() -> Result<()> {
158 let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
160 let a = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5)]);
161 let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;
162
163 let literal_expr = lit(42i32);
165 assert_eq!("42", format!("{literal_expr}"));
166
167 let literal_array = literal_expr
168 .evaluate(&batch)?
169 .into_array(batch.num_rows())
170 .expect("Failed to convert to array");
171 let literal_array = as_int32_array(&literal_array)?;
172
173 assert_eq!(literal_array.len(), 5); for i in 0..literal_array.len() {
176 assert_eq!(literal_array.value(i), 42);
177 }
178
179 Ok(())
180 }
181
182 #[test]
183 fn test_fmt_sql() -> Result<()> {
184 let expr = lit(42i32);
186 let display_string = expr.to_string();
187 assert_eq!(display_string, "42");
188 let sql_string = fmt_sql(expr.as_ref()).to_string();
189 assert_eq!(sql_string, "42");
190
191 Ok(())
192 }
193}