Skip to main content

datafusion_substrait/logical_plan/consumer/
substrait_consumer.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use super::{
6    from_aggregate_rel, from_cast, from_cross_rel, from_exchange_rel, from_fetch_rel,
7    from_field_reference, from_filter_rel, from_if_then, from_join_rel, from_literal,
8    from_nested, from_project_rel, from_read_rel, from_scalar_function, from_set_rel,
9    from_singular_or_list, from_sort_rel, from_subquery, from_substrait_rel,
10    from_substrait_rex, from_window_function,
11};
12use crate::extensions::Extensions;
13use crate::logical_plan::consumer::{
14    field_from_substrait_type_without_names, from_lambda,
15};
16use async_trait::async_trait;
17use datafusion::arrow::datatypes::{DataType, FieldRef};
18use datafusion::catalog::TableProvider;
19use datafusion::common::datatype::FieldExt;
20use datafusion::common::{
21    DFSchema, ScalarValue, TableReference, not_impl_err, substrait_err,
22};
23use datafusion::execution::{FunctionRegistry, SessionState};
24use datafusion::logical_expr::expr::LambdaVariable;
25use datafusion::logical_expr::{Expr, Extension, LogicalPlan};
26use std::collections::{HashMap, VecDeque};
27use std::sync::{Arc, RwLock};
28use substrait::proto::expression as substrait_expression;
29use substrait::proto::expression::{
30    Enum, FieldReference, IfThen, Literal, MultiOrList, Nested, ScalarFunction,
31    SingularOrList, SwitchExpression, WindowFunction,
32};
33use substrait::proto::{self, Type};
34use substrait::proto::{
35    AggregateRel, ConsistentPartitionWindowRel, CrossRel, DynamicParameter, ExchangeRel,
36    Expression, ExtensionLeafRel, ExtensionMultiRel, ExtensionSingleRel, FetchRel,
37    FilterRel, JoinRel, ProjectRel, ReadRel, Rel, SetRel, SortRel, r#type,
38};
39
40#[async_trait]
41/// This trait is used to consume Substrait plans, converting them into DataFusion Logical Plans.
42/// It can be implemented by users to allow for custom handling of relations, expressions, etc.
43///
44/// Combined with the [crate::logical_plan::producer::SubstraitProducer] this allows for fully
45/// customizable Substrait serde.
46///
47/// # Example Usage
48///
49/// ```
50/// # use async_trait::async_trait;
51/// # use datafusion::catalog::TableProvider;
52/// # use datafusion::common::{not_impl_err, substrait_err, DFSchema, ScalarValue, TableReference};
53/// # use datafusion::error::Result;
54/// # use datafusion::execution::{FunctionRegistry, SessionState};
55/// # use datafusion::logical_expr::{Expr, LogicalPlan, LogicalPlanBuilder};
56/// # use std::sync::Arc;
57/// # use substrait::proto;
58/// # use substrait::proto::{ExtensionLeafRel, FilterRel, ProjectRel, Type};
59/// # use datafusion::arrow::datatypes::DataType;
60/// # use datafusion::logical_expr::expr::ScalarFunction;
61/// # use datafusion_substrait::extensions::Extensions;
62/// # use datafusion_substrait::logical_plan::consumer::{
63/// #     from_project_rel, from_substrait_rel, from_substrait_rex, SubstraitConsumer, DefaultSubstraitLambdaConsumer
64/// # };
65///
66/// struct CustomSubstraitConsumer {
67///     extensions: Arc<Extensions>,
68///     state: Arc<SessionState>,
69///     // You can reuse existing consumer code related to lambdas
70///     lambda_consumer: DefaultSubstraitLambdaConsumer,
71/// }
72///
73/// #[async_trait]
74/// impl SubstraitConsumer for CustomSubstraitConsumer {
75///     async fn resolve_table_ref(
76///         &self,
77///         table_ref: &TableReference,
78///     ) -> Result<Option<Arc<dyn TableProvider>>> {
79///         let table = table_ref.table().to_string();
80///         let schema = self.state.schema_for_ref(table_ref.clone())?;
81///         let table_provider = schema.table(&table).await?;
82///         Ok(table_provider)
83///     }
84///
85///     fn get_extensions(&self) -> &Extensions {
86///         self.extensions.as_ref()
87///     }
88///
89///     fn get_function_registry(&self) -> &impl FunctionRegistry {
90///         self.state.as_ref()
91///     }
92///
93///     fn push_lambda_parameters(
94///        &self,
95///        lambda_parameters: &[Type],
96///        input_schema: &DFSchema,
97///    ) -> datafusion::common::Result<Vec<String>> {
98///        self.lambda_consumer.push_lambda_parameters(
99///            self,
100///            lambda_parameters,
101///            input_schema,
102///        )
103///    }
104///
105///     fn pop_lambda_parameters(&self) {
106///        self.lambda_consumer.pop_lambda_parameters();
107///    }
108///
109///    fn lambda_variable(
110///        &self,
111///        steps_out: usize,
112///        field_idx: usize,
113///    ) -> datafusion::common::Result<Expr> {
114///        self.lambda_consumer.lambda_variable(steps_out, field_idx)
115///    }
116///
117///     // You can reuse existing consumer code to assist in handling advanced extensions
118///     async fn consume_project(&self, rel: &ProjectRel) -> Result<LogicalPlan> {
119///         let df_plan = from_project_rel(self, rel).await?;
120///         if let Some(advanced_extension) = rel.advanced_extension.as_ref() {
121///             not_impl_err!(
122///                 "decode and handle an advanced extension: {:?}",
123///                 advanced_extension
124///             )
125///         } else {
126///             Ok(df_plan)
127///         }
128///     }
129///
130///     // You can implement a fully custom consumer method if you need special handling
131///     async fn consume_filter(&self, rel: &FilterRel) -> Result<LogicalPlan> {
132///         let input = self.consume_rel(rel.input.as_ref().unwrap()).await?;
133///         let expression =
134///             self.consume_expression(rel.condition.as_ref().unwrap(), input.schema())
135///                 .await?;
136///         // though this one is quite boring
137///         LogicalPlanBuilder::from(input).filter(expression)?.build()
138///     }
139///
140///     // You can add handlers for extension relations
141///     async fn consume_extension_leaf(
142///         &self,
143///         rel: &ExtensionLeafRel,
144///     ) -> Result<LogicalPlan> {
145///         not_impl_err!(
146///             "handle protobuf Any {} as you need",
147///             rel.detail.as_ref().unwrap().type_url
148///         )
149///     }
150///
151///     // and handlers for user-define types
152///     fn consume_user_defined_type(&self, typ: &proto::r#type::UserDefined) -> Result<DataType> {
153///         let type_string = self.extensions.types.get(&typ.type_reference).unwrap();
154///         match type_string.as_str() {
155///             "u!foo" => not_impl_err!("handle foo conversion"),
156///             "u!bar" => not_impl_err!("handle bar conversion"),
157///             _ => substrait_err!("unexpected type")
158///         }
159///     }
160///
161///     // and user-defined literals
162///     fn consume_user_defined_literal(&self, literal: &proto::expression::literal::UserDefined) -> Result<ScalarValue> {
163///         // extract type_reference from the new TypeAnchorType oneof
164///         let type_ref = match literal.type_anchor_type {
165///             Some(proto::expression::literal::user_defined::TypeAnchorType::TypeReference(r)) => r,
166///             Some(proto::expression::literal::user_defined::TypeAnchorType::TypeAliasReference(_)) => {
167///                 return not_impl_err!("Type alias references are not yet supported")
168///             }
169///             None => 0,
170///         };
171///         let type_string = self.extensions.types.get(&type_ref).unwrap();
172///         match type_string.as_str() {
173///             "u!foo" => not_impl_err!("handle foo conversion"),
174///             "u!bar" => not_impl_err!("handle bar conversion"),
175///             _ => substrait_err!("unexpected type")
176///         }
177///     }
178/// }
179/// ```
180pub trait SubstraitConsumer: Send + Sync + Sized {
181    async fn resolve_table_ref(
182        &self,
183        table_ref: &TableReference,
184    ) -> datafusion::common::Result<Option<Arc<dyn TableProvider>>>;
185
186    // TODO: Remove these two methods
187    //   Ideally, the abstract consumer should not place any constraints on implementations.
188    //   The functionality for which the Extensions and FunctionRegistry is needed should be abstracted
189    //   out into methods on the trait. As an example, resolve_table_reference is such a method.
190    //   See: https://github.com/apache/datafusion/issues/13863
191    fn get_extensions(&self) -> &Extensions;
192    fn get_function_registry(&self) -> &impl FunctionRegistry;
193
194    // Relation Methods
195    // There is one method per Substrait relation to allow for easy overriding of consumer behaviour.
196    // These methods have default implementations calling the common handler code, to allow for users
197    // to re-use common handling logic.
198
199    /// All [Rel]s to be converted pass through this method.
200    /// You can provide your own implementation if you wish to customize the conversion behaviour.
201    async fn consume_rel(&self, rel: &Rel) -> datafusion::common::Result<LogicalPlan> {
202        from_substrait_rel(self, rel).await
203    }
204
205    async fn consume_read(
206        &self,
207        rel: &ReadRel,
208    ) -> datafusion::common::Result<LogicalPlan> {
209        from_read_rel(self, rel).await
210    }
211
212    async fn consume_filter(
213        &self,
214        rel: &FilterRel,
215    ) -> datafusion::common::Result<LogicalPlan> {
216        from_filter_rel(self, rel).await
217    }
218
219    async fn consume_fetch(
220        &self,
221        rel: &FetchRel,
222    ) -> datafusion::common::Result<LogicalPlan> {
223        from_fetch_rel(self, rel).await
224    }
225
226    async fn consume_aggregate(
227        &self,
228        rel: &AggregateRel,
229    ) -> datafusion::common::Result<LogicalPlan> {
230        from_aggregate_rel(self, rel).await
231    }
232
233    async fn consume_sort(
234        &self,
235        rel: &SortRel,
236    ) -> datafusion::common::Result<LogicalPlan> {
237        from_sort_rel(self, rel).await
238    }
239
240    async fn consume_join(
241        &self,
242        rel: &JoinRel,
243    ) -> datafusion::common::Result<LogicalPlan> {
244        from_join_rel(self, rel).await
245    }
246
247    async fn consume_project(
248        &self,
249        rel: &ProjectRel,
250    ) -> datafusion::common::Result<LogicalPlan> {
251        from_project_rel(self, rel).await
252    }
253
254    async fn consume_set(&self, rel: &SetRel) -> datafusion::common::Result<LogicalPlan> {
255        from_set_rel(self, rel).await
256    }
257
258    async fn consume_cross(
259        &self,
260        rel: &CrossRel,
261    ) -> datafusion::common::Result<LogicalPlan> {
262        from_cross_rel(self, rel).await
263    }
264
265    async fn consume_consistent_partition_window(
266        &self,
267        _rel: &ConsistentPartitionWindowRel,
268    ) -> datafusion::common::Result<LogicalPlan> {
269        not_impl_err!("Consistent Partition Window Rel not supported")
270    }
271
272    async fn consume_exchange(
273        &self,
274        rel: &ExchangeRel,
275    ) -> datafusion::common::Result<LogicalPlan> {
276        from_exchange_rel(self, rel).await
277    }
278
279    // Expression Methods
280    // There is one method per Substrait expression to allow for easy overriding of consumer behaviour
281    // These methods have default implementations calling the common handler code, to allow for users
282    // to re-use common handling logic.
283
284    /// All [Expression]s to be converted pass through this method.
285    /// You can provide your own implementation if you wish to customize the conversion behaviour.
286    async fn consume_expression(
287        &self,
288        expr: &Expression,
289        input_schema: &DFSchema,
290    ) -> datafusion::common::Result<Expr> {
291        from_substrait_rex(self, expr, input_schema).await
292    }
293
294    async fn consume_literal(&self, expr: &Literal) -> datafusion::common::Result<Expr> {
295        from_literal(self, expr).await
296    }
297
298    async fn consume_field_reference(
299        &self,
300        expr: &FieldReference,
301        input_schema: &DFSchema,
302    ) -> datafusion::common::Result<Expr> {
303        from_field_reference(self, expr, input_schema).await
304    }
305
306    async fn consume_scalar_function(
307        &self,
308        expr: &ScalarFunction,
309        input_schema: &DFSchema,
310    ) -> datafusion::common::Result<Expr> {
311        from_scalar_function(self, expr, input_schema).await
312    }
313
314    async fn consume_window_function(
315        &self,
316        expr: &WindowFunction,
317        input_schema: &DFSchema,
318    ) -> datafusion::common::Result<Expr> {
319        from_window_function(self, expr, input_schema).await
320    }
321
322    async fn consume_if_then(
323        &self,
324        expr: &IfThen,
325        input_schema: &DFSchema,
326    ) -> datafusion::common::Result<Expr> {
327        from_if_then(self, expr, input_schema).await
328    }
329
330    async fn consume_switch(
331        &self,
332        _expr: &SwitchExpression,
333        _input_schema: &DFSchema,
334    ) -> datafusion::common::Result<Expr> {
335        not_impl_err!("Switch expression not supported")
336    }
337
338    async fn consume_singular_or_list(
339        &self,
340        expr: &SingularOrList,
341        input_schema: &DFSchema,
342    ) -> datafusion::common::Result<Expr> {
343        from_singular_or_list(self, expr, input_schema).await
344    }
345
346    async fn consume_multi_or_list(
347        &self,
348        _expr: &MultiOrList,
349        _input_schema: &DFSchema,
350    ) -> datafusion::common::Result<Expr> {
351        not_impl_err!("Multi Or List expression not supported")
352    }
353
354    async fn consume_cast(
355        &self,
356        expr: &substrait_expression::Cast,
357        input_schema: &DFSchema,
358    ) -> datafusion::common::Result<Expr> {
359        from_cast(self, expr, input_schema).await
360    }
361
362    async fn consume_subquery(
363        &self,
364        expr: &substrait_expression::Subquery,
365        input_schema: &DFSchema,
366    ) -> datafusion::common::Result<Expr> {
367        from_subquery(self, expr, input_schema).await
368    }
369
370    async fn consume_nested(
371        &self,
372        expr: &Nested,
373        input_schema: &DFSchema,
374    ) -> datafusion::common::Result<Expr> {
375        from_nested(self, expr, input_schema).await
376    }
377
378    async fn consume_enum(
379        &self,
380        _expr: &Enum,
381        _input_schema: &DFSchema,
382    ) -> datafusion::common::Result<Expr> {
383        not_impl_err!("Enum expression not supported")
384    }
385
386    async fn consume_dynamic_parameter(
387        &self,
388        expr: &DynamicParameter,
389        _input_schema: &DFSchema,
390    ) -> datafusion::common::Result<Expr> {
391        let id = format!("${}", expr.parameter_reference + 1);
392        let field = expr
393            .r#type
394            .as_ref()
395            .map(|t| {
396                super::from_substrait_type_without_names(self, t).map(|dt| {
397                    Arc::new(datafusion::arrow::datatypes::Field::new(&id, dt, true))
398                })
399            })
400            .transpose()?;
401        Ok(Expr::Placeholder(
402            datafusion::logical_expr::expr::Placeholder::new_with_field(id, field),
403        ))
404    }
405
406    async fn consume_lambda(
407        &self,
408        expr: &proto::expression::Lambda,
409        input_schema: &DFSchema,
410    ) -> datafusion::common::Result<Expr> {
411        from_lambda(self, expr, input_schema).await
412    }
413
414    // Outer Schema Stack
415    // These methods manage a stack of outer schemas for correlated subquery support.
416    // When entering a subquery, the enclosing query's schema is pushed onto the stack.
417    // Field references with OuterReference root_type use these to resolve columns.
418
419    /// Push an outer schema onto the stack when entering a subquery.
420    fn push_outer_schema(&self, _schema: Arc<DFSchema>) {}
421
422    /// Pop an outer schema from the stack when leaving a subquery.
423    fn pop_outer_schema(&self) {}
424
425    /// Get the outer schema at the given nesting depth.
426    /// `steps_out = 1` is the immediately enclosing query, `steps_out = 2`
427    /// is two levels out, etc. Returns `None` if `steps_out` is 0 or
428    /// exceeds the current nesting depth (the caller should treat this as
429    /// an error in the Substrait plan).
430    fn get_outer_schema(&self, _steps_out: usize) -> Option<Arc<DFSchema>> {
431        None
432    }
433
434    // User-Defined Functionality
435
436    // The details of extension relations, and how to handle them, are fully up to users to specify.
437    // The following methods allow users to customize the consumer behaviour
438
439    async fn consume_extension_leaf(
440        &self,
441        rel: &ExtensionLeafRel,
442    ) -> datafusion::common::Result<LogicalPlan> {
443        if let Some(detail) = rel.detail.as_ref() {
444            return substrait_err!(
445                "Missing handler for ExtensionLeafRel: {}",
446                detail.type_url
447            );
448        }
449        substrait_err!("Missing handler for ExtensionLeafRel")
450    }
451
452    async fn consume_extension_single(
453        &self,
454        rel: &ExtensionSingleRel,
455    ) -> datafusion::common::Result<LogicalPlan> {
456        if let Some(detail) = rel.detail.as_ref() {
457            return substrait_err!(
458                "Missing handler for ExtensionSingleRel: {}",
459                detail.type_url
460            );
461        }
462        substrait_err!("Missing handler for ExtensionSingleRel")
463    }
464
465    async fn consume_extension_multi(
466        &self,
467        rel: &ExtensionMultiRel,
468    ) -> datafusion::common::Result<LogicalPlan> {
469        if let Some(detail) = rel.detail.as_ref() {
470            return substrait_err!(
471                "Missing handler for ExtensionMultiRel: {}",
472                detail.type_url
473            );
474        }
475        substrait_err!("Missing handler for ExtensionMultiRel")
476    }
477
478    // Users can bring their own types to Substrait which require custom handling
479
480    fn consume_user_defined_type(
481        &self,
482        user_defined_type: &r#type::UserDefined,
483    ) -> datafusion::common::Result<DataType> {
484        substrait_err!(
485            "Missing handler for user-defined type: {}",
486            user_defined_type.type_reference
487        )
488    }
489
490    /// Optional Arrow field metadata for a Substrait type.
491    ///
492    /// Arrow cannot represent some Substrait types natively. A user-defined
493    /// "json" type, for example, becomes a plain `DataType::Utf8`, which loses
494    /// the fact that the values are JSON. A consumer can return metadata here
495    /// to keep the original type recoverable from the Arrow schema.
496    ///
497    /// The consumer sees the whole [`Type`], so it can key the metadata off a
498    /// user-defined type, a type variation, or anything else it recognizes.
499    /// The metadata is attached to the Arrow [`Field`] built for this type,
500    /// including a type nested inside a list, map, or struct.
501    ///
502    /// The default attaches nothing.
503    ///
504    /// [`Field`]: datafusion::arrow::datatypes::Field
505    fn consume_type_metadata(
506        &self,
507        _typ: &Type,
508    ) -> datafusion::common::Result<Option<HashMap<String, String>>> {
509        Ok(None)
510    }
511
512    fn consume_user_defined_literal(
513        &self,
514        user_defined_literal: &proto::expression::literal::UserDefined,
515    ) -> datafusion::common::Result<ScalarValue> {
516        let type_ref = match user_defined_literal.type_anchor_type {
517            Some(
518                proto::expression::literal::user_defined::TypeAnchorType::TypeReference(
519                    ref_val,
520                ),
521            ) => ref_val,
522            Some(
523                proto::expression::literal::user_defined::TypeAnchorType::TypeAliasReference(_),
524            ) => {
525                return not_impl_err!(
526                    "Type alias references in user-defined literals are not yet supported"
527                )
528            }
529            None => 0,
530        };
531        substrait_err!("Missing handler for user-defined literals {}", type_ref)
532    }
533
534    // Lambda related methods
535
536    /// Push the given lambda parameters onto the stack when entering a lambda and
537    /// returns the names they got assigned
538    ///
539    /// Note for custom implementations it's possible to embed a [DefaultSubstraitLambdaConsumer] and forward this method to it
540    fn push_lambda_parameters(
541        &self,
542        _lambda_parameters: &[Type],
543        _input_schema: &DFSchema,
544    ) -> datafusion::common::Result<Vec<String>> {
545        not_impl_err!("SubstraitConsumer::push_lambda_parameters")
546    }
547
548    /// Pop lambda parameters from the stack when leaving a lambda.
549    fn pop_lambda_parameters(&self) {}
550
551    /// Returns an expression corresponding to the lambda variable with the given field_idx within the lambda it originates from,
552    /// at the lambda `step_outs` of the current scope
553    ///
554    /// Note for custom implementations it's possible to embed a [DefaultSubstraitLambdaConsumer] and forward this method to it
555    fn lambda_variable(
556        &self,
557        _steps_out: usize,
558        _field_idx: usize,
559    ) -> datafusion::common::Result<Expr> {
560        not_impl_err!("SubstraitConsumer::lambda_variable")
561    }
562}
563
564/// Default SubstraitConsumer for converting standard Substrait without user-defined extensions.
565///
566/// Used as the consumer in [crate::logical_plan::consumer::from_substrait_plan]
567pub struct DefaultSubstraitConsumer<'a> {
568    pub(super) extensions: &'a Extensions,
569    pub(super) state: &'a SessionState,
570    outer_schemas: RwLock<Vec<Arc<DFSchema>>>,
571    lambda_consumer: DefaultSubstraitLambdaConsumer,
572}
573
574impl<'a> DefaultSubstraitConsumer<'a> {
575    pub fn new(extensions: &'a Extensions, state: &'a SessionState) -> Self {
576        DefaultSubstraitConsumer {
577            extensions,
578            state,
579            outer_schemas: RwLock::new(Vec::new()),
580            lambda_consumer: DefaultSubstraitLambdaConsumer::new(),
581        }
582    }
583}
584
585#[async_trait]
586impl SubstraitConsumer for DefaultSubstraitConsumer<'_> {
587    async fn resolve_table_ref(
588        &self,
589        table_ref: &TableReference,
590    ) -> datafusion::common::Result<Option<Arc<dyn TableProvider>>> {
591        let table = table_ref.table().to_string();
592        let schema = self.state.schema_for_ref(table_ref.clone())?;
593        let table_provider = schema.table(&table).await?;
594        Ok(table_provider)
595    }
596
597    fn get_extensions(&self) -> &Extensions {
598        self.extensions
599    }
600
601    fn get_function_registry(&self) -> &impl FunctionRegistry {
602        self.state
603    }
604
605    fn push_outer_schema(&self, schema: Arc<DFSchema>) {
606        self.outer_schemas.write().unwrap().push(schema);
607    }
608
609    fn pop_outer_schema(&self) {
610        self.outer_schemas.write().unwrap().pop();
611    }
612
613    fn get_outer_schema(&self, steps_out: usize) -> Option<Arc<DFSchema>> {
614        let schemas = self.outer_schemas.read().unwrap();
615        // steps_out=1 → last element, steps_out=2 → second-to-last, etc.
616        // Returns None for steps_out=0 or steps_out > stack depth.
617        schemas
618            .len()
619            .checked_sub(steps_out)
620            .and_then(|idx| schemas.get(idx).cloned())
621    }
622
623    async fn consume_extension_leaf(
624        &self,
625        rel: &ExtensionLeafRel,
626    ) -> datafusion::common::Result<LogicalPlan> {
627        let Some(ext_detail) = &rel.detail else {
628            return substrait_err!("Unexpected empty detail in ExtensionLeafRel");
629        };
630        let plan = self
631            .state
632            .serializer_registry()
633            .deserialize_logical_plan(&ext_detail.type_url, &ext_detail.value)?;
634        Ok(LogicalPlan::Extension(Extension { node: plan }))
635    }
636
637    async fn consume_extension_single(
638        &self,
639        rel: &ExtensionSingleRel,
640    ) -> datafusion::common::Result<LogicalPlan> {
641        let Some(ext_detail) = &rel.detail else {
642            return substrait_err!("Unexpected empty detail in ExtensionSingleRel");
643        };
644        let plan = self
645            .state
646            .serializer_registry()
647            .deserialize_logical_plan(&ext_detail.type_url, &ext_detail.value)?;
648        let Some(input_rel) = &rel.input else {
649            return substrait_err!(
650                "ExtensionSingleRel missing input rel, try using ExtensionLeafRel instead"
651            );
652        };
653        let input_plan = self.consume_rel(input_rel).await?;
654        let plan = plan.with_exprs_and_inputs(plan.expressions(), vec![input_plan])?;
655        Ok(LogicalPlan::Extension(Extension { node: plan }))
656    }
657
658    async fn consume_extension_multi(
659        &self,
660        rel: &ExtensionMultiRel,
661    ) -> datafusion::common::Result<LogicalPlan> {
662        let Some(ext_detail) = &rel.detail else {
663            return substrait_err!("Unexpected empty detail in ExtensionMultiRel");
664        };
665        let plan = self
666            .state
667            .serializer_registry()
668            .deserialize_logical_plan(&ext_detail.type_url, &ext_detail.value)?;
669        let mut inputs = Vec::with_capacity(rel.inputs.len());
670        for input in &rel.inputs {
671            let input_plan = self.consume_rel(input).await?;
672            inputs.push(input_plan);
673        }
674        let plan = plan.with_exprs_and_inputs(plan.expressions(), inputs)?;
675        Ok(LogicalPlan::Extension(Extension { node: plan }))
676    }
677
678    fn push_lambda_parameters(
679        &self,
680        lambda_parameters: &[Type],
681        input_schema: &DFSchema,
682    ) -> datafusion::common::Result<Vec<String>> {
683        self.lambda_consumer
684            .push_lambda_parameters(self, lambda_parameters, input_schema)
685    }
686
687    fn pop_lambda_parameters(&self) {
688        self.lambda_consumer.pop_lambda_parameters()
689    }
690
691    fn lambda_variable(
692        &self,
693        steps_out: usize,
694        field_idx: usize,
695    ) -> datafusion::common::Result<Expr> {
696        self.lambda_consumer.lambda_variable(steps_out, field_idx)
697    }
698}
699
700/// Default implementation of lambda related methods of the [SubstraitConsumer] trait
701///
702/// Can be embedded into a custom [SubstraitConsumer] to implement them
703pub struct DefaultSubstraitLambdaConsumer {
704    inner: RwLock<DefaultSubstraitLambdaConsumerInner>,
705}
706
707struct DefaultSubstraitLambdaConsumerInner {
708    /// Parameters of the lambdas currently in scope, ordered from innermost
709    /// to outermost. Index 0 is the lambda being consumed; higher indices
710    /// are enclosing lambdas, matching the `steps_out` value used by
711    /// [`DefaultSubstraitLambdaConsumer::lambda_variable`] and `LambdaParameterReference`.
712    lambda_parameters: VecDeque<Vec<FieldRef>>,
713    next_lambda_parameter: usize,
714}
715
716impl Default for DefaultSubstraitLambdaConsumer {
717    fn default() -> Self {
718        Self::new()
719    }
720}
721
722impl DefaultSubstraitLambdaConsumer {
723    pub fn new() -> Self {
724        Self {
725            inner: RwLock::new(DefaultSubstraitLambdaConsumerInner {
726                lambda_parameters: VecDeque::new(),
727                next_lambda_parameter: 0,
728            }),
729        }
730    }
731
732    pub fn push_lambda_parameters(
733        &self,
734        consumer: &impl SubstraitConsumer,
735        lambda_parameters: &[Type],
736        input_schema: &DFSchema,
737    ) -> datafusion::common::Result<Vec<String>> {
738        let mut inner = self.inner.write().unwrap();
739
740        let lambda_parameters = lambda_parameters
741            .iter()
742            .map(|ty| {
743                let (assigned_number, default_name) =
744                    next_lambda_parameter_name(inner.next_lambda_parameter, input_schema);
745
746                inner.next_lambda_parameter = assigned_number + 1;
747
748                Ok(field_from_substrait_type_without_names(consumer, ty)?
749                    .renamed(&default_name))
750            })
751            .collect::<datafusion::common::Result<Vec<_>>>()?;
752
753        let names = lambda_parameters.iter().map(|f| f.name().clone()).collect();
754
755        inner.lambda_parameters.push_front(lambda_parameters);
756
757        Ok(names)
758    }
759
760    pub fn pop_lambda_parameters(&self) {
761        self.inner.write().unwrap().lambda_parameters.pop_front();
762    }
763
764    pub fn lambda_variable(
765        &self,
766        steps_out: usize,
767        field_idx: usize,
768    ) -> datafusion::common::Result<Expr> {
769        let lambda_parameters = &self.inner.read().unwrap().lambda_parameters;
770
771        let Some(lambda_parameters) = lambda_parameters.get(steps_out) else {
772            return substrait_err!(
773                "No lambda at {steps_out} steps out, got only {}",
774                lambda_parameters.len()
775            );
776        };
777
778        let Some(var) = lambda_parameters.get(field_idx) else {
779            return substrait_err!(
780                "At lambda {steps_out} steps out, no field at index {field_idx}, got only {}",
781                lambda_parameters.len()
782            );
783        };
784
785        Ok(Expr::LambdaVariable(LambdaVariable::new(
786            var.name().clone(),
787            Some(Arc::clone(var)),
788        )))
789    }
790}
791
792/// Returns the next available lambda parameter name and the index it was assigned.
793///
794/// Names follow the pattern `pN` where `N` starts at `next_lambda_parameter`. If `pN`
795/// conflicts with an existing column name in `input_schema`, `N` is incremented until
796/// a free name is found.
797fn next_lambda_parameter_name(
798    mut next_lambda_parameter: usize,
799    input_schema: &DFSchema,
800) -> (usize, String) {
801    loop {
802        let name = format!("p{next_lambda_parameter}");
803
804        // avoid conflicts with column names
805        if !input_schema.has_column_with_unqualified_name(&name) {
806            return (next_lambda_parameter, name);
807        }
808
809        next_lambda_parameter += 1;
810    }
811}
812
813#[cfg(test)]
814mod tests {
815    use super::*;
816    use crate::logical_plan::consumer::utils::tests::test_consumer;
817    use datafusion::arrow::datatypes::{Field, Schema};
818
819    fn make_schema(fields: &[(&str, DataType)]) -> Arc<DFSchema> {
820        let arrow_fields: Vec<Field> = fields
821            .iter()
822            .map(|(name, dt)| Field::new(*name, dt.clone(), true))
823            .collect();
824        Arc::new(
825            DFSchema::try_from(Schema::new(arrow_fields))
826                .expect("failed to create schema"),
827        )
828    }
829
830    #[test]
831    fn test_get_outer_schema_empty_stack() {
832        let consumer = test_consumer();
833
834        // No schemas pushed — any steps_out should return None
835        assert!(consumer.get_outer_schema(0).is_none());
836        assert!(consumer.get_outer_schema(1).is_none());
837        assert!(consumer.get_outer_schema(2).is_none());
838    }
839
840    #[test]
841    fn test_get_outer_schema_single_level() {
842        let consumer = test_consumer();
843
844        let schema_a = make_schema(&[("a", DataType::Int64)]);
845        consumer.push_outer_schema(Arc::clone(&schema_a));
846
847        // steps_out=1 returns the one pushed schema
848        let result = consumer.get_outer_schema(1).unwrap();
849        assert_eq!(result.fields().len(), 1);
850        assert_eq!(result.fields()[0].name(), "a");
851
852        // steps_out=0 and steps_out=2 are out of range
853        assert!(consumer.get_outer_schema(0).is_none());
854        assert!(consumer.get_outer_schema(2).is_none());
855
856        consumer.pop_outer_schema();
857        assert!(consumer.get_outer_schema(1).is_none());
858    }
859
860    #[test]
861    fn test_get_outer_schema_nested() {
862        let consumer = test_consumer();
863
864        let schema_a = make_schema(&[("a", DataType::Int64)]);
865        let schema_b = make_schema(&[("b", DataType::Utf8)]);
866
867        consumer.push_outer_schema(Arc::clone(&schema_a));
868        consumer.push_outer_schema(Arc::clone(&schema_b));
869
870        // steps_out=1 returns the most recent (schema_b)
871        let result = consumer.get_outer_schema(1).unwrap();
872        assert_eq!(result.fields()[0].name(), "b");
873
874        // steps_out=2 returns the grandparent (schema_a)
875        let result = consumer.get_outer_schema(2).unwrap();
876        assert_eq!(result.fields()[0].name(), "a");
877
878        // steps_out=3 exceeds depth
879        assert!(consumer.get_outer_schema(3).is_none());
880
881        // Pop one level — now steps_out=1 returns schema_a
882        consumer.pop_outer_schema();
883        let result = consumer.get_outer_schema(1).unwrap();
884        assert_eq!(result.fields()[0].name(), "a");
885        assert!(consumer.get_outer_schema(2).is_none());
886    }
887}