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 fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 std::fmt::Display::fmt(self, f)
99 }
100}
101
102pub 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 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 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 assert_eq!(literal_array.len(), 5); 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 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}