bubulalabu commented on code in PR #18224:
URL: https://github.com/apache/datafusion/pull/18224#discussion_r2456466252
##########
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:
If the extension of the public API is an option, the following trait would
be ideal to implement correlated table functions:
```
pub trait StreamingTableFunctionImpl: Send + Sync + Debug {
fn name(&self) -> &str;
fn signature(&self) -> &Signature;
fn return_type(&self, arg_types: &[DataType]) -> Result<Schema>;
fn create_plan(
&self,
args: Vec<Arc<dyn PhysicalExpr>>,
input: Arc<dyn ExecutionPlan>,
projected_schema: SchemaRef,
) -> Result<Arc<dyn ExecutionPlan>>;
}
```
--
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]