datafusion_physical_expr/expressions/
lambda_variable.rs1use std::hash::Hash;
8use std::sync::Arc;
9
10use crate::physical_expr::PhysicalExpr;
11use arrow::datatypes::FieldRef;
12use arrow::{
13 datatypes::{DataType, Schema},
14 record_batch::RecordBatch,
15};
16
17use datafusion_common::{Result, exec_err, internal_err};
18use datafusion_expr::ColumnarValue;
19
20#[derive(Debug, Clone)]
22pub struct LambdaVariable {
23 index: usize,
24 field: FieldRef,
25}
26
27impl Eq for LambdaVariable {}
28
29impl PartialEq for LambdaVariable {
30 fn eq(&self, other: &Self) -> bool {
31 self.index == other.index && self.field == other.field
32 }
33}
34
35impl Hash for LambdaVariable {
36 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
37 self.index.hash(state);
38 self.field.hash(state);
39 }
40}
41
42impl LambdaVariable {
43 pub fn new(index: usize, field: FieldRef) -> Self {
45 Self { index, field }
46 }
47
48 pub fn name(&self) -> &str {
50 self.field.name()
51 }
52
53 pub fn index(&self) -> usize {
55 self.index
56 }
57
58 pub fn field(&self) -> &FieldRef {
60 &self.field
61 }
62
63 #[cfg(feature = "proto")]
64 pub fn try_from_proto(
66 node: &datafusion_proto_models::protobuf::PhysicalExprNode,
67 _ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
68 ) -> Result<Arc<dyn PhysicalExpr>> {
69 use datafusion_physical_expr_common::{
70 expect_expr_variant, physical_expr::proto_decode::require_proto_field,
71 };
72 use datafusion_proto_models::protobuf;
73
74 let var = expect_expr_variant!(
75 node,
76 protobuf::physical_expr_node::ExprType::LambdaVariable,
77 "LambdaVariable",
78 );
79 let protobuf::PhysicalLambdaVariableExprNode { index, field } = var;
80
81 Ok(Arc::new(LambdaVariable::new(
82 *index as usize,
83 Arc::new(
84 require_proto_field(field.as_ref(), "LambdaVariable", "field")?
85 .try_into()?,
86 ),
87 )))
88 }
89}
90
91impl std::fmt::Display for LambdaVariable {
92 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
93 write!(f, "{}@{}", self.name(), self.index)
94 }
95}
96
97impl PhysicalExpr for LambdaVariable {
98 fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
99 Ok(self.field.data_type().clone())
100 }
101
102 fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
103 Ok(self.field.is_nullable())
104 }
105
106 fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
107 if self.index >= batch.num_columns() {
108 return internal_err!(
109 "PhysicalExpr LambdaVariable references column '{}' at index {} (zero-based) but batch only has {} columns: {:?}",
110 self.name(),
111 self.index,
112 batch.num_columns(),
113 batch
114 .schema_ref()
115 .fields()
116 .iter()
117 .map(|f| f.name())
118 .collect::<Vec<_>>()
119 );
120 }
121
122 if self.field.as_ref() != batch.schema_ref().field(self.index) {
123 return exec_err!(
124 "Field of physical LambdaVariable with index {} doesn't match batch field during evaluation {} != {}",
125 self.index,
126 self.field,
127 batch.schema_ref().field(self.index)
128 );
129 }
130
131 Ok(ColumnarValue::Array(Arc::clone(batch.column(self.index))))
132 }
133
134 fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> {
135 Ok(Arc::clone(&self.field))
136 }
137
138 fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
139 vec![]
140 }
141
142 fn with_new_children(
143 self: Arc<Self>,
144 _children: Vec<Arc<dyn PhysicalExpr>>,
145 ) -> Result<Arc<dyn PhysicalExpr>> {
146 Ok(self)
147 }
148
149 fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150 write!(f, "{}@{}", self.name(), self.index)
151 }
152
153 #[cfg(feature = "proto")]
154 fn try_to_proto(
155 &self,
156 _ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
157 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
158 use datafusion_proto_models::protobuf;
159
160 let Self { index, field } = self;
164
165 Ok(Some(protobuf::PhysicalExprNode {
166 expr_id: None,
167 expr_type: Some(protobuf::physical_expr_node::ExprType::LambdaVariable(
168 protobuf::PhysicalLambdaVariableExprNode {
169 index: *index as u32,
170 field: Some(field.as_ref().try_into()?),
171 },
172 )),
173 }))
174 }
175}
176
177pub fn lambda_variable(name: &str, schema: &Schema) -> Result<Arc<dyn PhysicalExpr>> {
179 let index = schema.index_of(name)?;
180 let field = Arc::clone(&schema.fields()[index]);
181
182 Ok(Arc::new(LambdaVariable::new(index, field)))
183}
184
185#[cfg(all(test, feature = "proto"))]
187mod proto_tests {
188 use super::*;
189 use crate::proto_test_util::{StubEncoder, UnreachableDecoder, column_node};
190 use arrow::datatypes::Field;
191 use datafusion_common::DataFusionError;
192 use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
193 use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
194 use datafusion_proto_models::protobuf::{self, physical_expr_node};
195
196 fn v_field() -> FieldRef {
197 Arc::new(Field::new("v", DataType::Int32, true))
198 }
199
200 #[test]
201 fn try_to_proto_encodes_lambda_variable() {
202 let var = LambdaVariable::new(3, v_field());
203 let encoder = StubEncoder::ok();
205 let ctx = PhysicalExprEncodeCtx::new(&encoder);
206
207 let node = var
208 .try_to_proto(&ctx)
209 .unwrap()
210 .expect("LambdaVariable should encode to Some(node)");
211
212 assert!(node.expr_id.is_none());
213 let protobuf::PhysicalLambdaVariableExprNode { index, field } =
214 match node.expr_type {
215 Some(physical_expr_node::ExprType::LambdaVariable(v)) => v,
216 other => panic!("expected a LambdaVariable node, got {other:?}"),
217 };
218 assert_eq!(index, 3);
219 let field = field.expect("field should be encoded");
220 assert_eq!(field.name, "v");
221 assert!(field.nullable);
222 }
223
224 #[test]
225 fn try_from_proto_rejects_non_lambda_variable_node() {
226 let node = column_node("a");
227 let schema = Schema::empty();
228 let decoder = UnreachableDecoder;
229 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
230
231 let err = LambdaVariable::try_from_proto(&node, &ctx).unwrap_err();
232 assert!(
233 matches!(err, DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a LambdaVariable"))
234 );
235 }
236
237 #[test]
238 fn try_from_proto_rejects_missing_field() {
239 let node = protobuf::PhysicalExprNode {
240 expr_id: None,
241 expr_type: Some(physical_expr_node::ExprType::LambdaVariable(
242 protobuf::PhysicalLambdaVariableExprNode {
243 index: 0,
244 field: None,
245 },
246 )),
247 };
248 let schema = Schema::empty();
249 let decoder = UnreachableDecoder;
250 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
251
252 let err = LambdaVariable::try_from_proto(&node, &ctx).unwrap_err();
253 assert!(
254 matches!(err, DataFusionError::Internal(msg) if msg.contains("LambdaVariable is missing required field 'field'"))
255 );
256 }
257
258 #[test]
261 fn lambda_variable_proto_roundtrip() {
262 let var = LambdaVariable::new(5, v_field());
263 let encoder = StubEncoder::ok();
264 let enc_ctx = PhysicalExprEncodeCtx::new(&encoder);
265
266 let node = var
267 .try_to_proto(&enc_ctx)
268 .unwrap()
269 .expect("LambdaVariable should encode to Some(node)");
270
271 let schema = Schema::empty();
272 let decoder = UnreachableDecoder;
273 let dec_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
274
275 let decoded = LambdaVariable::try_from_proto(&node, &dec_ctx).unwrap();
276 let decoded = decoded
277 .downcast_ref::<LambdaVariable>()
278 .expect("decoded expr should be a LambdaVariable");
279
280 assert_eq!(decoded, &var);
281 }
282}