alamb commented on code in PR #18224:
URL: https://github.com/apache/datafusion/pull/18224#discussion_r2453133807
##########
datafusion/sql/src/relation/join.rs:
##########
@@ -177,6 +197,122 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
.build(),
}
}
+
+ /// Try to create a LateralTableFunction node if the relation is a table
function
+ /// with outer references. Returns None if this is not a lateral table
function case.
+ fn try_create_lateral_table_function(
+ &self,
+ left: &LogicalPlan,
+ relation: &TableFactor,
+ planner_context: &mut PlannerContext,
+ ) -> Result<Option<LogicalPlan>> {
+ // Check if this is a table function call (either Table or Function
variant)
+ let (tbl_func_name, func_args_vec, alias) = match relation {
+ TableFactor::Table {
+ name,
+ args: Some(func_args),
+ alias,
+ ..
+ } => {
+ let name_str = name
+ .0
+ .first()
+ .and_then(|ident| ident.as_ident())
+ .ok_or_else(|| plan_datafusion_err!("Invalid table
function name"))?
+ .to_string();
+ (name_str, func_args.args.clone(), alias.as_ref())
+ }
+ TableFactor::Function {
+ name, args, alias, ..
+ } => {
+ let name_str = name
+ .0
+ .first()
+ .and_then(|ident| ident.as_ident())
+ .ok_or_else(|| plan_datafusion_err!("Invalid function
name"))?
+ .to_string();
+ (name_str, args.clone(), alias.as_ref())
+ }
+ _ => return Ok(None),
+ };
+
+ // Parse arguments to expressions
+ // Use the outer from schema so that column references are properly
recognized
+ let schema_for_args = planner_context
+ .outer_from_schema()
+ .unwrap_or_else(|| Arc::new(DFSchema::empty()));
+
+ let args = func_args_vec
+ .iter()
+ .map(|arg| {
+ if let FunctionArg::Unnamed(FunctionArgExpr::Expr(expr)) = arg
{
+ self.sql_expr_to_logical_expr(
+ expr.clone(),
+ &schema_for_args,
+ planner_context,
+ )
+ } else {
+ plan_err!("Unsupported function argument type")
+ }
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ // LATERAL functions evaluate row-by-row when referencing outer columns
+ let has_column_refs = args.iter().any(|expr| {
+ matches!(expr, Expr::Column(_)) || expr.contains_outer()
+ });
+
+ if has_column_refs {
+ // For table functions with outer references, we need to get the
schema
+ // but can't actually call the function yet (outer refs not
resolved).
+ // We'll replace outer references with placeholder literals to get
the schema.
+ let placeholder_args: Vec<Expr> = args
+ .iter()
+ .enumerate()
+ .map(|(idx, arg)| {
+ if matches!(arg, Expr::Column(_)) || arg.contains_outer() {
+ let data_type = arg.get_type(&schema_for_args)?;
+
+ // Use incrementing values (1, 2, 3...) to ensure
valid ranges for functions
+ // like generate_series(start, end) where start < end
+ let val = (idx + 1) as i64;
+
+ let placeholder =
+ ScalarValue::try_new_placeholder(&data_type, val)?;
+
+ Ok(Expr::Literal(placeholder, None))
+ } else {
+ Ok(arg.clone())
+ }
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ let provider = self
+ .context_provider
+ .get_table_function_source(&tbl_func_name, placeholder_args)?;
Review Comment:
Maybe it would be simpler we added a new function to the table provider so
it could report its schema rather than making a fake set of arguments just to
instantiate the function to get the schema
##########
datafusion/core/src/execution/lateral_table_function.rs:
##########
@@ -0,0 +1,450 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Execution plan for LATERAL table functions
+
+use std::any::Any;
+use std::fmt;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use arrow::array::ArrayRef;
+use arrow::compute::concat_batches;
+use arrow::datatypes::SchemaRef;
+use arrow::record_batch::RecordBatch;
+use datafusion_catalog::TableFunction;
+use datafusion_common::{internal_err, Result, ScalarValue};
+use datafusion_execution::TaskContext;
+use datafusion_expr::{ColumnarValue, Expr};
+use datafusion_physical_expr::{EquivalenceProperties, PhysicalExpr};
+use datafusion_physical_plan::{
+ DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties,
PlanProperties,
+ RecordBatchStream, SendableRecordBatchStream,
+};
+use futures::future::BoxFuture;
+use futures::stream::Stream;
+use futures::{ready, FutureExt, StreamExt};
+
+use crate::execution::session_state::SessionState;
+
+/// Execution plan for LATERAL table functions
Review Comment:
does this mirror the implementation in another system (e.g. duckdb)? It
seems very special purpose
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]