Skip to main content

datafusion_physical_expr/
planner.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 std::sync::Arc;
6
7use crate::scalar_subquery::ScalarSubqueryExpr;
8use crate::{HigherOrderFunctionExpr, ScalarFunctionExpr};
9use crate::{
10    PhysicalExpr,
11    expressions::{self, Column, Literal, binary, like, similar_to},
12};
13
14use arrow::datatypes::Schema;
15use datafusion_common::config::ConfigOptions;
16use datafusion_common::datatype::FieldExt;
17use datafusion_common::metadata::FieldMetadata;
18use datafusion_common::{
19    DFSchema, Result, ScalarValue, TableReference, ToDFSchema, exec_err,
20    internal_datafusion_err, not_impl_err, plan_datafusion_err, plan_err,
21};
22use datafusion_expr::execution_props::ExecutionProps;
23use datafusion_expr::expr::{
24    Alias, Cast, HigherOrderFunction, InList, Lambda, LambdaVariable, Placeholder,
25    ScalarFunction,
26};
27use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
28use datafusion_expr::var_provider::VarType;
29use datafusion_expr::var_provider::is_system_variables;
30use datafusion_expr::{
31    Between, BinaryExpr, Expr, ExprSchemable, Like, Operator, TryCast, binary_expr, lit,
32};
33
34/// [PhysicalExpr] evaluate DataFusion expressions such as `A + 1`, or `CAST(c1
35/// AS int)`.
36///
37/// [PhysicalExpr] are the physical counterpart to [Expr] used in logical
38/// planning, and can be evaluated directly on a [RecordBatch]. They are
39/// normally created from [Expr] by a [PhysicalPlanner] and can be created
40/// directly using [create_physical_expr].
41///
42/// A Physical expression knows its type, nullability and how to evaluate itself.
43///
44/// [PhysicalPlanner]: https://docs.rs/datafusion/latest/datafusion/physical_planner/trait.PhysicalPlanner.html
45/// [RecordBatch]: https://docs.rs/arrow/latest/arrow/record_batch/struct.RecordBatch.html
46///
47/// # Example: Create `PhysicalExpr` from `Expr`
48/// ```
49/// # use arrow::datatypes::{DataType, Field, Schema};
50/// # use datafusion_common::DFSchema;
51/// # use datafusion_expr::{Expr, col, lit};
52/// # use datafusion_physical_expr::create_physical_expr;
53/// # use datafusion_expr::execution_props::ExecutionProps;
54/// # use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
55/// // For a logical expression `a = 1`, we can create a physical expression
56/// let expr = col("a").eq(lit(1));
57/// // To create a PhysicalExpr we need 1. a schema
58/// let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
59/// let df_schema = DFSchema::try_from(schema).unwrap();
60/// // 2. ExecutionProps
61/// let props = ExecutionProps::new();
62/// // We can now create a PhysicalExpr. Expressions with no scalar
63/// // subqueries use an empty `PhysicalPlanningContext`:
64/// let physical_expr =
65///     create_physical_expr(&expr, &df_schema, &props, &PhysicalPlanningContext::default())
66///         .unwrap();
67/// ```
68///
69/// # Example: Executing a PhysicalExpr to obtain [ColumnarValue]
70/// ```
71/// # use std::sync::Arc;
72/// # use arrow::array::{cast::AsArray, BooleanArray, Int32Array, RecordBatch};
73/// # use arrow::datatypes::{DataType, Field, Schema};
74/// # use datafusion_common::{assert_batches_eq, DFSchema};
75/// # use datafusion_expr::{Expr, col, lit, ColumnarValue};
76/// # use datafusion_physical_expr::create_physical_expr;
77/// # use datafusion_expr::execution_props::ExecutionProps;
78/// # use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
79/// # let expr = col("a").eq(lit(1));
80/// # let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
81/// # let df_schema = DFSchema::try_from(schema.clone()).unwrap();
82/// # let props = ExecutionProps::new();
83/// // Given a PhysicalExpr, for `a = 1` we can evaluate it against a RecordBatch like this:
84/// let physical_expr =
85///     create_physical_expr(&expr, &df_schema, &props, &PhysicalPlanningContext::default())
86///         .unwrap();
87/// // Input of [1,2,3]
88/// let input_batch = RecordBatch::try_from_iter(vec![
89///   ("a", Arc::new(Int32Array::from(vec![1, 2, 3])) as _)
90/// ]).unwrap();
91/// // The result is a ColumnarValue (either an Array or a Scalar)
92/// let result = physical_expr.evaluate(&input_batch).unwrap();
93/// // In this case, a BooleanArray with the result of the comparison
94/// let ColumnarValue::Array(arr) = result else {
95///  panic!("Expected an array")
96/// };
97/// assert_eq!(arr.as_boolean(), &BooleanArray::from(vec![true, false, false]));
98/// ```
99///
100/// [ColumnarValue]: datafusion_expr::ColumnarValue
101///
102/// Create a physical expression from a logical expression ([Expr]).
103///
104/// # Arguments
105///
106/// * `e` - The logical expression
107/// * `input_dfschema` - The DataFusion schema for the input, used to resolve `Column` references
108///   to qualified or unqualified fields by name.
109/// * `execution_props` - Per-execution properties such as the query start time.
110/// * `planning_ctx` - The [`PhysicalPlanningContext`] used to resolve
111///   `Expr::ScalarSubquery` and `Expr::LambdaVariable` nodes. The physical
112///   planner threads the subquery index map and shared results container from
113///   its `ScalarSubqueryExec` construction into calls to
114///   `create_physical_expr`; the lambda variable qualifiers are added by this
115///   function itself as it descends into lambda bodies. Callers creating
116///   physical expressions outside of physical planning should pass
117///   `&PhysicalPlanningContext::default()`; converting a scalar subquery then returns a
118///   planning error.
119#[cfg_attr(feature = "recursive_protection", recursive::recursive)]
120pub fn create_physical_expr(
121    e: &Expr,
122    input_dfschema: &DFSchema,
123    execution_props: &ExecutionProps,
124    planning_ctx: &PhysicalPlanningContext,
125) -> Result<Arc<dyn PhysicalExpr>> {
126    let input_schema = input_dfschema.as_arrow();
127
128    match e {
129        Expr::Alias(Alias { expr, metadata, .. }) => {
130            if let Expr::Literal(v, prior_metadata) = expr.as_ref() {
131                let new_metadata = FieldMetadata::merge_options(
132                    prior_metadata.as_ref(),
133                    metadata.as_ref(),
134                );
135                Ok(Arc::new(Literal::new_with_metadata(
136                    v.clone(),
137                    new_metadata,
138                )))
139            } else {
140                Ok(create_physical_expr(
141                    expr,
142                    input_dfschema,
143                    execution_props,
144                    planning_ctx,
145                )?)
146            }
147        }
148        Expr::Column(c) => {
149            let idx = input_dfschema.index_of_column(c)?;
150            Ok(Arc::new(Column::new(&c.name, idx)))
151        }
152        Expr::Literal(value, metadata) => Ok(Arc::new(Literal::new_with_metadata(
153            value.clone(),
154            metadata.clone(),
155        ))),
156        Expr::ScalarVariable(_, variable_names) => {
157            if is_system_variables(variable_names) {
158                match execution_props.get_var_provider(VarType::System) {
159                    Some(provider) => {
160                        let scalar_value = provider.get_value(variable_names.clone())?;
161                        Ok(Arc::new(Literal::new(scalar_value)))
162                    }
163                    _ => plan_err!("No system variable provider found"),
164                }
165            } else {
166                match execution_props.get_var_provider(VarType::UserDefined) {
167                    Some(provider) => {
168                        let scalar_value = provider.get_value(variable_names.clone())?;
169                        Ok(Arc::new(Literal::new(scalar_value)))
170                    }
171                    _ => plan_err!("No user defined variable provider found"),
172                }
173            }
174        }
175        Expr::IsTrue(expr) => {
176            let binary_op = binary_expr(
177                expr.as_ref().clone(),
178                Operator::IsNotDistinctFrom,
179                lit(true),
180            );
181            create_physical_expr(
182                &binary_op,
183                input_dfschema,
184                execution_props,
185                planning_ctx,
186            )
187        }
188        Expr::IsNotTrue(expr) => {
189            let binary_op =
190                binary_expr(expr.as_ref().clone(), Operator::IsDistinctFrom, lit(true));
191            create_physical_expr(
192                &binary_op,
193                input_dfschema,
194                execution_props,
195                planning_ctx,
196            )
197        }
198        Expr::IsFalse(expr) => {
199            let binary_op = binary_expr(
200                expr.as_ref().clone(),
201                Operator::IsNotDistinctFrom,
202                lit(false),
203            );
204            create_physical_expr(
205                &binary_op,
206                input_dfschema,
207                execution_props,
208                planning_ctx,
209            )
210        }
211        Expr::IsNotFalse(expr) => {
212            let binary_op =
213                binary_expr(expr.as_ref().clone(), Operator::IsDistinctFrom, lit(false));
214            create_physical_expr(
215                &binary_op,
216                input_dfschema,
217                execution_props,
218                planning_ctx,
219            )
220        }
221        Expr::IsUnknown(expr) => {
222            let binary_op = binary_expr(
223                expr.as_ref().clone(),
224                Operator::IsNotDistinctFrom,
225                Expr::Literal(ScalarValue::Boolean(None), None),
226            );
227            create_physical_expr(
228                &binary_op,
229                input_dfschema,
230                execution_props,
231                planning_ctx,
232            )
233        }
234        Expr::IsNotUnknown(expr) => {
235            let binary_op = binary_expr(
236                expr.as_ref().clone(),
237                Operator::IsDistinctFrom,
238                Expr::Literal(ScalarValue::Boolean(None), None),
239            );
240            create_physical_expr(
241                &binary_op,
242                input_dfschema,
243                execution_props,
244                planning_ctx,
245            )
246        }
247        Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
248            // Create physical expressions for left and right operands
249            let lhs = create_physical_expr(
250                left,
251                input_dfschema,
252                execution_props,
253                planning_ctx,
254            )?;
255            let rhs = create_physical_expr(
256                right,
257                input_dfschema,
258                execution_props,
259                planning_ctx,
260            )?;
261            // Note that the logical planner is responsible
262            // for type coercion on the arguments (e.g. if one
263            // argument was originally Int32 and one was
264            // Int64 they will both be coerced to Int64).
265            //
266            // There should be no coercion during physical
267            // planning.
268            binary(lhs, *op, rhs, input_schema)
269        }
270        Expr::Like(Like {
271            negated,
272            expr,
273            pattern,
274            escape_char,
275            case_insensitive,
276        }) => {
277            // `\` is the implicit escape, see https://github.com/apache/datafusion/issues/13291
278            if escape_char.unwrap_or('\\') != '\\' {
279                return exec_err!(
280                    "LIKE does not support escape_char other than the backslash (\\)"
281                );
282            }
283            let physical_expr = create_physical_expr(
284                expr,
285                input_dfschema,
286                execution_props,
287                planning_ctx,
288            )?;
289            let physical_pattern = create_physical_expr(
290                pattern,
291                input_dfschema,
292                execution_props,
293                planning_ctx,
294            )?;
295            like(
296                *negated,
297                *case_insensitive,
298                physical_expr,
299                physical_pattern,
300                input_schema,
301            )
302        }
303        Expr::SimilarTo(Like {
304            negated,
305            expr,
306            pattern,
307            escape_char,
308            case_insensitive,
309        }) => {
310            if escape_char.is_some() {
311                return exec_err!("SIMILAR TO does not support escape_char yet");
312            }
313            let physical_expr = create_physical_expr(
314                expr,
315                input_dfschema,
316                execution_props,
317                planning_ctx,
318            )?;
319            let physical_pattern = create_physical_expr(
320                pattern,
321                input_dfschema,
322                execution_props,
323                planning_ctx,
324            )?;
325            similar_to(*negated, *case_insensitive, physical_expr, physical_pattern)
326        }
327        Expr::Case(case) => {
328            let expr: Option<Arc<dyn PhysicalExpr>> = if let Some(e) = &case.expr {
329                Some(create_physical_expr(
330                    e.as_ref(),
331                    input_dfschema,
332                    execution_props,
333                    planning_ctx,
334                )?)
335            } else {
336                None
337            };
338            let (when_expr, then_expr): (Vec<&Expr>, Vec<&Expr>) = case
339                .when_then_expr
340                .iter()
341                .map(|(w, t)| (w.as_ref(), t.as_ref()))
342                .unzip();
343            let when_expr = create_physical_exprs(
344                when_expr,
345                input_dfschema,
346                execution_props,
347                planning_ctx,
348            )?;
349            let then_expr = create_physical_exprs(
350                then_expr,
351                input_dfschema,
352                execution_props,
353                planning_ctx,
354            )?;
355            let when_then_expr: Vec<(Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>)> =
356                when_expr
357                    .iter()
358                    .zip(then_expr.iter())
359                    .map(|(w, t)| (Arc::clone(w), Arc::clone(t)))
360                    .collect();
361            let else_expr: Option<Arc<dyn PhysicalExpr>> =
362                if let Some(e) = &case.else_expr {
363                    Some(create_physical_expr(
364                        e.as_ref(),
365                        input_dfschema,
366                        execution_props,
367                        planning_ctx,
368                    )?)
369                } else {
370                    None
371                };
372            Ok(expressions::case(expr, when_then_expr, else_expr)?)
373        }
374        Expr::Cast(Cast { expr, field }) => expressions::cast_with_target_field(
375            create_physical_expr(expr, input_dfschema, execution_props, planning_ctx)?,
376            input_schema,
377            field,
378            None,
379        ),
380        Expr::TryCast(TryCast { expr, field }) => {
381            expressions::try_cast_with_target_field(
382                create_physical_expr(
383                    expr,
384                    input_dfschema,
385                    execution_props,
386                    planning_ctx,
387                )?,
388                input_schema,
389                field,
390            )
391        }
392        Expr::Not(expr) => expressions::not(create_physical_expr(
393            expr,
394            input_dfschema,
395            execution_props,
396            planning_ctx,
397        )?),
398        Expr::Negative(expr) => expressions::negative(
399            create_physical_expr(expr, input_dfschema, execution_props, planning_ctx)?,
400            input_schema,
401        ),
402        Expr::IsNull(expr) => expressions::is_null(create_physical_expr(
403            expr,
404            input_dfschema,
405            execution_props,
406            planning_ctx,
407        )?),
408        Expr::IsNotNull(expr) => expressions::is_not_null(create_physical_expr(
409            expr,
410            input_dfschema,
411            execution_props,
412            planning_ctx,
413        )?),
414        Expr::ScalarFunction(ScalarFunction { func, args }) => {
415            let physical_args = create_physical_exprs(
416                args,
417                input_dfschema,
418                execution_props,
419                planning_ctx,
420            )?;
421            let config_options = match execution_props.config_options.as_ref() {
422                Some(config_options) => Arc::clone(config_options),
423                None => Arc::new(ConfigOptions::default()),
424            };
425
426            Ok(Arc::new(ScalarFunctionExpr::try_new(
427                Arc::clone(func),
428                physical_args,
429                input_schema,
430                config_options,
431            )?))
432        }
433        Expr::Between(Between {
434            expr,
435            negated,
436            low,
437            high,
438        }) => {
439            let value_expr = create_physical_expr(
440                expr,
441                input_dfschema,
442                execution_props,
443                planning_ctx,
444            )?;
445            let low_expr =
446                create_physical_expr(low, input_dfschema, execution_props, planning_ctx)?;
447            let high_expr = create_physical_expr(
448                high,
449                input_dfschema,
450                execution_props,
451                planning_ctx,
452            )?;
453
454            // rewrite the between into the two binary operators
455            let binary_expr = binary(
456                binary(
457                    Arc::clone(&value_expr),
458                    Operator::GtEq,
459                    low_expr,
460                    input_schema,
461                )?,
462                Operator::And,
463                binary(
464                    Arc::clone(&value_expr),
465                    Operator::LtEq,
466                    high_expr,
467                    input_schema,
468                )?,
469                input_schema,
470            );
471
472            if *negated {
473                expressions::not(binary_expr?)
474            } else {
475                binary_expr
476            }
477        }
478        Expr::InList(InList {
479            expr,
480            list,
481            negated,
482        }) => match expr.as_ref() {
483            Expr::Literal(ScalarValue::Utf8(None), _) => {
484                Ok(expressions::lit(ScalarValue::Boolean(None)))
485            }
486            _ => {
487                let value_expr = create_physical_expr(
488                    expr,
489                    input_dfschema,
490                    execution_props,
491                    planning_ctx,
492                )?;
493
494                let list_exprs = create_physical_exprs(
495                    list,
496                    input_dfschema,
497                    execution_props,
498                    planning_ctx,
499                )?;
500                expressions::in_list(value_expr, list_exprs, negated, input_schema)
501            }
502        },
503        Expr::ScalarSubquery(sq) => {
504            match planning_ctx.index_of(sq) {
505                Some(index) => {
506                    let schema = sq.subquery.schema();
507                    if schema.fields().len() != 1 {
508                        return plan_err!(
509                            "Scalar subquery must return exactly one column, got {}",
510                            schema.fields().len()
511                        );
512                    }
513                    let output_field = schema.field(0);
514                    let metadata = FieldMetadata::from(output_field.as_ref());
515                    Ok(Arc::new(ScalarSubqueryExpr::new_with_metadata(
516                        output_field.data_type().clone(),
517                        e.nullable(input_dfschema)?,
518                        (!metadata.is_empty()).then_some(metadata),
519                        index,
520                        planning_ctx.results().clone(),
521                    )))
522                }
523                None => {
524                    // Not found: either a correlated subquery that wasn't
525                    // rewritten to a join, or an uncorrelated one that wasn't
526                    // registered by the physical planner.
527                    not_impl_err!(
528                        "Physical plan does not support logical expression {e:?}"
529                    )
530                }
531            }
532        }
533        Expr::Placeholder(Placeholder { id, .. }) => {
534            exec_err!("Placeholder '{id}' was not provided a value for execution.")
535        }
536        Expr::HigherOrderFunction(invocation @ HigherOrderFunction { func, args }) => {
537            let num_lambdas = args
538                .iter()
539                .filter(|arg| matches!(arg, Expr::Lambda(_)))
540                .count();
541
542            let mut lambda_parameters =
543                invocation.lambda_parameters(input_dfschema)?.into_iter();
544
545            if num_lambdas > lambda_parameters.len() {
546                return plan_err!(
547                    "{} lambda_parameters returned only {} values for {num_lambdas} lambdas",
548                    func.name(),
549                    lambda_parameters.len()
550                );
551            }
552
553            let lambda_qualifier = 1 + input_dfschema
554                .iter()
555                .filter_map(|(qualifier, _field)| {
556                    qualifier.and_then(|tbl| {
557                        tbl.table().strip_prefix("lambda_")?.parse::<usize>().ok()
558                    })
559                })
560                .max()
561                .unwrap_or_default();
562
563            let qualifier = TableReference::bare(format!("lambda_{lambda_qualifier}"));
564
565            let physical_args = args
566                .iter()
567                .map(|arg| match arg {
568                    Expr::Lambda(lambda) => {
569                        let lambda_parameters = lambda_parameters
570                            .next()
571                            .ok_or_else(|| {
572                                internal_datafusion_err!(
573                                    "lambda_parameters len should have been checked above"
574                                )
575                            })?
576                            .into_iter()
577                            .zip(&lambda.params)
578                            .map(|(field, name)| {
579                                (Some(qualifier.clone()), field.renamed(name.as_str()))
580                            });
581
582                        let new_fields = input_dfschema
583                            .iter()
584                            .map(|(tbl, field)| (tbl.cloned(), Arc::clone(field)))
585                            .chain(lambda_parameters)
586                            .collect();
587
588                        let lambda_schema = DFSchema::new_with_metadata(
589                            new_fields,
590                            input_dfschema.metadata().clone(),
591                        )?;
592
593                        let planning_ctx = planning_ctx
594                            .clone()
595                            .with_qualified_lambda_variables(&qualifier, &lambda.params);
596
597                        create_physical_expr(
598                            arg,
599                            &lambda_schema,
600                            execution_props,
601                            &planning_ctx,
602                        )
603                    }
604                    _ => create_physical_expr(
605                        arg,
606                        input_dfschema,
607                        execution_props,
608                        planning_ctx,
609                    ),
610                })
611                .collect::<Result<_>>()?;
612
613            let config_options = match execution_props.config_options.as_ref() {
614                Some(config_options) => Arc::clone(config_options),
615                None => Arc::new(ConfigOptions::default()),
616            };
617
618            Ok(Arc::new(HigherOrderFunctionExpr::try_new_with_schema(
619                Arc::clone(func),
620                physical_args,
621                input_schema,
622                config_options,
623            )?))
624        }
625        Expr::Lambda(Lambda { params, body }) => expressions::lambda(
626            params,
627            create_physical_expr(body, input_dfschema, execution_props, planning_ctx)?,
628        ),
629        Expr::LambdaVariable(LambdaVariable {
630            name,
631            field,
632            spans: _,
633        }) => {
634            let field = field.as_ref().ok_or_else(|| {
635                plan_datafusion_err!("unresolved LambdaVariable {name}")
636            })?;
637
638            let qualifier =
639                planning_ctx
640                    .lambda_variable_qualifier(name)
641                    .ok_or_else(|| {
642                        plan_datafusion_err!(
643                            "qualifier for lambda variable {name} not found"
644                        )
645                    })?;
646
647            let index = input_dfschema
648                .index_of_column_by_name(Some(qualifier), name)
649                .ok_or_else(|| {
650                    plan_datafusion_err!(
651                        "lambda variable {qualifier}.{name} not found in planning schema"
652                    )
653                })?;
654
655            let schema_field = input_dfschema.field(index);
656
657            // LambdaVariable.field will be made optional as in Expr::Placeholder
658            // and only LambdaVariable.name used, and field.name ignored,
659            // so they're not enforced to match for logical expressions
660            // Rename the field to match the schema one and use it's PartialEq impl instead
661            // of checking property by property and fail if new properties get's added to it.
662            // While not necessary, the sql planner does create lambda vars with matching names,
663            // so this shouldn't allocate with a lambda var from it
664            let renamed_field = Arc::clone(field).renamed(name);
665
666            if &renamed_field != schema_field {
667                return plan_err!(
668                    "LambdaVariable field and schema field mismatch {} != {}",
669                    renamed_field,
670                    schema_field
671                );
672            }
673
674            Ok(Arc::new(expressions::LambdaVariable::new(
675                index,
676                Arc::clone(schema_field),
677            )))
678        }
679        // Window and aggregate functions are evaluated by dedicated plan
680        // nodes, never by a physical expression. Reaching this point means
681        // the function is in a position where it cannot be evaluated, so
682        // report that instead of dumping the internal representation.
683        Expr::WindowFunction(_) => plan_err!(
684            "Window function '{e}' is not supported in this position. Window functions are supported in the SELECT list, ORDER BY, DISTINCT ON and QUALIFY"
685        ),
686        Expr::AggregateFunction(_) => plan_err!(
687            "Aggregate function '{e}' is not supported in this position. Aggregate functions are supported in the SELECT list, HAVING and ORDER BY of a query with GROUP BY"
688        ),
689        other => {
690            not_impl_err!("Physical plan does not support logical expression {other:?}")
691        }
692    }
693}
694
695/// Create vector of Physical Expression from a vector of logical expression
696///
697/// See [`create_physical_expr`] for details on the `planning_ctx` argument.
698pub fn create_physical_exprs<'a, I>(
699    exprs: I,
700    input_dfschema: &DFSchema,
701    execution_props: &ExecutionProps,
702    planning_ctx: &PhysicalPlanningContext,
703) -> Result<Vec<Arc<dyn PhysicalExpr>>>
704where
705    I: IntoIterator<Item = &'a Expr>,
706{
707    exprs
708        .into_iter()
709        .map(|expr| {
710            create_physical_expr(expr, input_dfschema, execution_props, planning_ctx)
711        })
712        .collect()
713}
714
715/// Convert a logical expression to a physical expression (without any simplification, etc)
716pub fn logical2physical(expr: &Expr, schema: &Schema) -> Arc<dyn PhysicalExpr> {
717    // TODO this makes a deep copy of the Schema. Should take SchemaRef instead and avoid deep copy
718    let df_schema = schema.clone().to_dfschema().unwrap();
719    let execution_props = ExecutionProps::new();
720    create_physical_expr(
721        expr,
722        &df_schema,
723        &execution_props,
724        &PhysicalPlanningContext::default(),
725    )
726    .unwrap()
727}
728
729#[cfg(test)]
730mod tests {
731    use arrow::array::{ArrayRef, BooleanArray, RecordBatch, StringArray};
732    use arrow::datatypes::{DataType, Field, Metadata};
733    use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY};
734    use datafusion_common::HashMap;
735    use datafusion_expr::physical_planning_context::{
736        ScalarSubqueryResults, SubqueryIndex,
737    };
738    use datafusion_expr::{LogicalPlanBuilder, col, scalar_subquery};
739
740    use super::*;
741
742    fn test_cast_schema() -> Schema {
743        Schema::new(vec![Field::new("a", DataType::Int32, false)])
744    }
745
746    fn lower_cast_expr(expr: &Expr, schema: &Schema) -> Result<Arc<dyn PhysicalExpr>> {
747        let df_schema = DFSchema::try_from(schema.clone())?;
748        create_physical_expr(
749            expr,
750            &df_schema,
751            &ExecutionProps::new(),
752            &PhysicalPlanningContext::default(),
753        )
754    }
755
756    fn as_planner_cast(physical: &Arc<dyn PhysicalExpr>) -> &expressions::CastExpr {
757        physical
758            .downcast_ref::<expressions::CastExpr>()
759            .expect("planner should lower logical CAST to CastExpr")
760    }
761
762    fn as_planner_try_cast(
763        physical: &Arc<dyn PhysicalExpr>,
764    ) -> &expressions::TryCastExpr {
765        physical
766            .downcast_ref::<expressions::TryCastExpr>()
767            .expect("planner should lower logical TRY_CAST to TryCastExpr")
768    }
769
770    #[test]
771    fn test_create_physical_expr_scalar_input_output() -> Result<()> {
772        let expr = col("letter").eq(lit("A"));
773
774        let schema = Schema::new(vec![Field::new("letter", DataType::Utf8, false)]);
775        let df_schema = DFSchema::try_from_qualified_schema("data", &schema)?;
776        let p = create_physical_expr(
777            &expr,
778            &df_schema,
779            &ExecutionProps::new(),
780            &PhysicalPlanningContext::default(),
781        )?;
782
783        let batch = RecordBatch::try_new(
784            Arc::new(schema),
785            vec![Arc::new(StringArray::from_iter_values(vec![
786                "A", "B", "C", "D",
787            ]))],
788        )?;
789        let result = p.evaluate(&batch)?;
790        let result = result.into_array(4).expect("Failed to convert to array");
791
792        assert_eq!(
793            &result,
794            &(Arc::new(BooleanArray::from(vec![true, false, false, false,])) as ArrayRef)
795        );
796
797        Ok(())
798    }
799
800    #[test]
801    fn scalar_subquery_nullability_accounts_for_min_rows() -> Result<()> {
802        for (produce_one_row, expected_nullable) in [(false, true), (true, false)] {
803            let plan = LogicalPlanBuilder::empty(produce_one_row)
804                .project(vec![lit(1)])?
805                .build()?;
806            let expr = scalar_subquery(Arc::new(plan));
807            let Expr::ScalarSubquery(subquery) = &expr else {
808                unreachable!()
809            };
810
811            let index = SubqueryIndex::new(0);
812            let planning_ctx = PhysicalPlanningContext::new(
813                HashMap::from([(subquery.clone(), index)]),
814                ScalarSubqueryResults::new(1),
815            );
816            let physical_expr = create_physical_expr(
817                &expr,
818                &DFSchema::empty(),
819                &ExecutionProps::new(),
820                &planning_ctx,
821            )?;
822
823            assert_eq!(physical_expr.nullable(&Schema::empty())?, expected_nullable);
824        }
825
826        Ok(())
827    }
828
829    #[test]
830    fn scalar_subquery_preserves_output_field_metadata() -> Result<()> {
831        let metadata = FieldMetadata::from(HashMap::from([(
832            EXTENSION_TYPE_NAME_KEY.to_string(),
833            "example.extension".to_string(),
834        )]));
835        let plan = LogicalPlanBuilder::empty(true)
836            .project(vec![
837                lit("a").alias_with_metadata("geometry", Some(metadata)),
838            ])?
839            .build()?;
840        let expr = scalar_subquery(Arc::new(plan));
841        let Expr::ScalarSubquery(subquery) = &expr else {
842            unreachable!()
843        };
844
845        let index = SubqueryIndex::new(0);
846        let planning_ctx = PhysicalPlanningContext::new(
847            HashMap::from([(subquery.clone(), index)]),
848            ScalarSubqueryResults::new(1),
849        );
850        let physical_expr = create_physical_expr(
851            &expr,
852            &DFSchema::empty(),
853            &ExecutionProps::new(),
854            &planning_ctx,
855        )?;
856
857        let field = physical_expr.return_field(&Schema::empty())?;
858        assert_eq!(
859            field.metadata().get(EXTENSION_TYPE_NAME_KEY),
860            Some(&"example.extension".to_string()),
861            "scalar subquery physical expr must keep ARROW extension metadata: {field:?}"
862        );
863        Ok(())
864    }
865
866    #[test]
867    fn test_cast_lowering_preserves_target_field_metadata() -> Result<()> {
868        let schema = test_cast_schema();
869
870        // Target field with both extension metadata and custom metadata.
871        // With exact target metadata semantics, all target metadata should propagate.
872        let target_field = Arc::new(
873            Field::new("cast_target", DataType::Int64, true).with_metadata(
874                Metadata::new()
875                    .with(EXTENSION_TYPE_NAME_KEY, "arrow.json")
876                    .with(EXTENSION_TYPE_METADATA_KEY, "{}")
877                    .with("custom_target_meta", "custom_value"),
878            ),
879        );
880        let cast_expr = Expr::Cast(Cast::new_from_field(
881            Box::new(col("a")),
882            Arc::clone(&target_field),
883        ));
884
885        let physical = lower_cast_expr(&cast_expr, &schema)?;
886        let cast = as_planner_cast(&physical);
887
888        // The CastExpr stores the target type and all target metadata
889        assert_eq!(cast.cast_type(), &DataType::Int64);
890        let target_metadata = cast.target_metadata().expect("should have metadata");
891        assert_eq!(
892            target_metadata.get(EXTENSION_TYPE_NAME_KEY),
893            Some(&"arrow.json".to_string())
894        );
895        assert_eq!(
896            target_metadata.get(EXTENSION_TYPE_METADATA_KEY),
897            Some(&"{}".to_string())
898        );
899        assert_eq!(cast.target_nullable(), Some(true));
900
901        // return_field should have all target metadata (exact semantics)
902        let returned = physical.return_field(&schema)?;
903        assert_eq!(
904            returned.metadata().get(EXTENSION_TYPE_NAME_KEY),
905            Some(&"arrow.json".to_string())
906        );
907        assert_eq!(
908            returned.metadata().get(EXTENSION_TYPE_METADATA_KEY),
909            Some(&"{}".to_string())
910        );
911        // All target metadata should propagate with exact semantics
912        assert_eq!(
913            returned.metadata().get("custom_target_meta"),
914            Some(&"custom_value".to_string()),
915            "All target metadata should propagate with exact semantics"
916        );
917        assert!(physical.nullable(&schema)?);
918
919        Ok(())
920    }
921
922    #[test]
923    fn test_cast_lowering_preserves_standard_cast_semantics() -> Result<()> {
924        let schema = test_cast_schema();
925        let cast_expr = Expr::Cast(Cast::new(Box::new(col("a")), DataType::Int64));
926
927        let physical = lower_cast_expr(&cast_expr, &schema)?;
928        let cast = as_planner_cast(&physical);
929        let returned_field = physical.return_field(&schema)?;
930
931        assert_eq!(cast.cast_type(), &DataType::Int64);
932        assert_eq!(returned_field.name(), "a");
933        assert_eq!(returned_field.data_type(), &DataType::Int64);
934        assert!(!physical.nullable(&schema)?);
935
936        Ok(())
937    }
938
939    #[test]
940    fn test_cast_lowering_preserves_same_type_field_semantics() -> Result<()> {
941        let schema = test_cast_schema();
942
943        // Same-type cast with extension metadata on target.
944        // With exact target metadata semantics, all target metadata should propagate.
945        let target_field = Arc::new(
946            Field::new("same_type_cast", DataType::Int32, true).with_metadata(
947                Metadata::new()
948                    .with(EXTENSION_TYPE_NAME_KEY, "arrow.opaque")
949                    .with("custom_meta", "custom_value"),
950            ),
951        );
952
953        for use_try_cast in [false, true] {
954            // For error labelling
955            let cast_name = if use_try_cast { "TRY_CAST" } else { "CAST" };
956
957            let cast_expr = if use_try_cast {
958                Expr::TryCast(TryCast::new_from_field(
959                    Box::new(col("a")),
960                    Arc::clone(&target_field),
961                ))
962            } else {
963                Expr::Cast(Cast::new_from_field(
964                    Box::new(col("a")),
965                    Arc::clone(&target_field),
966                ))
967            };
968
969            let physical = lower_cast_expr(&cast_expr, &schema)?;
970
971            // Extract common fields - both CastExpr and TryCastExpr have these
972            let (cast_type, target_metadata, target_nullable) = if use_try_cast {
973                let cast = as_planner_try_cast(&physical);
974                (cast.cast_type(), cast.target_metadata(), None)
975            } else {
976                let cast = as_planner_cast(&physical);
977                (
978                    cast.cast_type(),
979                    cast.target_metadata(),
980                    cast.target_nullable(),
981                )
982            };
983
984            // Verify the physical expression stores correct metadata (same for both)
985            assert_eq!(cast_type, &DataType::Int32, "{cast_name}: cast_type");
986            let target_metadata = target_metadata.expect("should have metadata");
987            assert_eq!(
988                target_metadata.get(EXTENSION_TYPE_NAME_KEY),
989                Some(&"arrow.opaque".to_string()),
990                "{cast_name}: extension type name"
991            );
992
993            // Only CastExpr tracks target_nullable (TryCast is always nullable)
994            if !use_try_cast {
995                assert_eq!(target_nullable, Some(true), "{cast_name}: target_nullable");
996            }
997
998            // return_field should have all target metadata (exact semantics)
999            let returned = physical.return_field(&schema)?;
1000            assert_eq!(
1001                returned.metadata().get(EXTENSION_TYPE_NAME_KEY),
1002                Some(&"arrow.opaque".to_string()),
1003                "{cast_name}: return_field extension type name"
1004            );
1005            // All target metadata should propagate with exact semantics
1006            assert_eq!(
1007                returned.metadata().get("custom_meta"),
1008                Some(&"custom_value".to_string()),
1009                "{cast_name}: All target metadata should propagate with exact semantics"
1010            );
1011            assert!(
1012                physical.nullable(&schema)?,
1013                "{cast_name}: should be nullable"
1014            );
1015        }
1016
1017        Ok(())
1018    }
1019
1020    /// Test that deeply nested expressions do not cause a stack overflow.
1021    ///
1022    /// This test only runs when the `recursive_protection` feature is enabled,
1023    /// as it would overflow the stack otherwise.
1024    #[test]
1025    #[cfg_attr(not(feature = "recursive_protection"), ignore)]
1026    fn test_deeply_nested_binary_expr() -> Result<()> {
1027        // Create a deeply nested binary expression tree: ((((a + a) + a) + a) + ... )
1028        // With 1000 levels of nesting, this would overflow the stack without recursion protection.
1029        let depth = 1000;
1030
1031        let mut expr = col("a");
1032        for _ in 0..depth {
1033            expr = Expr::BinaryExpr(BinaryExpr {
1034                left: Box::new(expr),
1035                op: Operator::Plus,
1036                right: Box::new(col("a")),
1037            });
1038        }
1039
1040        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
1041        let df_schema = DFSchema::try_from(schema)?;
1042
1043        // This should not stack overflow
1044        let _physical_expr = create_physical_expr(
1045            &expr,
1046            &df_schema,
1047            &ExecutionProps::new(),
1048            &PhysicalPlanningContext::default(),
1049        )?;
1050
1051        Ok(())
1052    }
1053}