Apache DataFusion SQL Query Engine
fix: Change `OuterReferenceColumn` to contain the entire outer field to prevent metadata loss (#17524)
Kristin Cowalcijk9e36ec46c5b1
diff --git a/datafusion/core/tests/user_defined/user_defined_scalar_functions.rs b/datafusion/core/tests/user_defined/user_defined_scalar_functions.rsindex a3a1101c81..e1c7a875e0 100644--- a/datafusion/core/tests/user_defined/user_defined_scalar_functions.rs+++ b/datafusion/core/tests/user_defined/user_defined_scalar_functions.rs@@ -1832,3 +1832,101 @@ async fn test_config_options_work_for_scalar_func() -> Result<()> {Ok(())}++/// https://github.com/apache/datafusion/issues/17422+#[tokio::test]+async fn test_extension_metadata_preserve_in_subquery() -> Result<()> {+ #[derive(Debug, PartialEq, Eq, Hash)]+ struct ExtensionScalarPredicate {+ signature: Signature,+ }++ impl Default for ExtensionScalarPredicate {+ fn default() -> Self {+ Self {+ signature: Signature::user_defined(Volatility::Immutable),+ }+ }+ }++ impl ScalarUDFImpl for ExtensionScalarPredicate {+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn name(&self) -> &str {+ "extension_predicate"+ }++ fn signature(&self) -> &Signature {+ &self.signature+ }++ fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {+ Ok(arg_types.to_vec())+ }++ fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {+ unreachable!("This shouldn't have been called")+ }++ fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {+ for arg in args.arg_fields {+ assert!(arg.metadata().contains_key("ARROW:extension:name"));+ }++ Ok(Field::new("", DataType::Boolean, true).into())+ }++ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {+ for arg in args.arg_fields {+ assert!(arg.metadata().contains_key("ARROW:extension:name"));+ }++ let array =+ ScalarValue::Boolean(Some(true)).to_array_of_size(args.number_rows)?;+ Ok(ColumnarValue::Array(array))+ }+ }++ let schema = Schema::new(vec![+ Field::new("id", DataType::Int64, true),+ Field::new("geometry", DataType::Utf8, true).with_metadata(HashMap::from([(+ "ARROW:extension:name".to_string(),+ "foofy.foofy".to_string(),+ )])),+ ]);++ let batch_lhs = RecordBatch::try_new(+ schema.clone().into(),+ vec![+ create_array!(Int64, [1, 2]),+ create_array!(Utf8, [Some("item1"), Some("item2")]),+ ],+ )?;++ let batch_rhs = RecordBatch::try_new(+ schema.clone().into(),+ vec![+ create_array!(Int64, [2, 3]),+ create_array!(Utf8, [Some("item2"), Some("item3")]),+ ],+ )?;++ let ctx = SessionContext::new();+ ctx.register_batch("l", batch_lhs)?;+ ctx.register_batch("r", batch_rhs)?;+ ctx.register_udf(ExtensionScalarPredicate::default().into());++ let df = ctx+ .sql(+ "+ SELECT L.id l_id FROM L+ WHERE EXISTS (SELECT 1 FROM R WHERE extension_predicate(L.geometry, R.geometry))+ ORDER BY l_id+ ",+ )+ .await?;+ assert!(!df.collect().await?.is_empty());+ Ok(())+}diff --git a/datafusion/expr/src/expr.rs b/datafusion/expr/src/expr.rsindex f72fb4c309..53db2dd7ac 100644--- a/datafusion/expr/src/expr.rs+++ b/datafusion/expr/src/expr.rs@@ -390,7 +390,7 @@ pub enum Expr {Placeholder(Placeholder),/// A placeholder which holds a reference to a qualified field/// in the outer query, used for correlated sub queries.- OuterReferenceColumn(DataType, Column),+ OuterReferenceColumn(FieldRef, Column),/// Unnest expressionUnnest(Unnest),}@@ -2871,8 +2871,8 @@ impl HashNode for Expr {Expr::Placeholder(place_holder) => {place_holder.hash(state);}- Expr::OuterReferenceColumn(data_type, column) => {- data_type.hash(state);+ Expr::OuterReferenceColumn(field, column) => {+ field.hash(state);column.hash(state);}Expr::Unnest(Unnest { expr: _expr }) => {}@@ -4103,7 +4103,7 @@ mod test {// If this test fails when you change `Expr`, please try// `Box`ing the fields to make `Expr` smaller// See https://github.com/apache/datafusion/issues/16199 for details- assert_eq!(size_of::<Expr>(), 128);+ assert_eq!(size_of::<Expr>(), 112);assert_eq!(size_of::<ScalarValue>(), 64);assert_eq!(size_of::<DataType>(), 24); // 3 ptrsassert_eq!(size_of::<Vec<Expr>>(), 24);diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rsindex 9da9772023..4d8b94ba27 100644--- a/datafusion/expr/src/expr_fn.rs+++ b/datafusion/expr/src/expr_fn.rs@@ -43,6 +43,7 @@ use datafusion_common::{plan_err, Column, Result, ScalarValue, Spans, TableReferuse datafusion_functions_window_common::field::WindowUDFFieldArgs;use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;use std::any::Any;+use std::collections::HashMap;use std::fmt::Debug;use std::hash::Hash;use std::ops::Not;@@ -69,8 +70,22 @@ pub fn col(ident: impl Into<Column>) -> Expr {/// Create an out reference column which hold a reference that has been resolved to a field/// outside of the current plan.+/// The expression created by this function does not preserve the metadata of the outer column.+/// Please use `out_ref_col_with_metadata` if you want to preserve the metadata.pub fn out_ref_col(dt: DataType, ident: impl Into<Column>) -> Expr {- Expr::OuterReferenceColumn(dt, ident.into())+ out_ref_col_with_metadata(dt, HashMap::new(), ident)+}++/// Create an out reference column from an existing field (preserving metadata)+pub fn out_ref_col_with_metadata(+ dt: DataType,+ metadata: HashMap<String, String>,+ ident: impl Into<Column>,+) -> Expr {+ let column = ident.into();+ let field: FieldRef =+ Arc::new(Field::new(column.name(), dt, true).with_metadata(metadata));+ Expr::OuterReferenceColumn(field, column)}/// Create an unqualified column expression from the provided name, without normalizingdiff --git a/datafusion/expr/src/expr_schema.rs b/datafusion/expr/src/expr_schema.rsindex 27f58d7d81..d0988514eb 100644--- a/datafusion/expr/src/expr_schema.rs+++ b/datafusion/expr/src/expr_schema.rs@@ -112,7 +112,7 @@ impl ExprSchemable for Expr {},Expr::Negative(expr) => expr.get_type(schema),Expr::Column(c) => Ok(schema.data_type(c)?.clone()),- Expr::OuterReferenceColumn(ty, _) => Ok(ty.clone()),+ Expr::OuterReferenceColumn(field, _) => Ok(field.data_type().clone()),Expr::ScalarVariable(ty, _) => Ok(ty.clone()),Expr::Literal(l, _) => Ok(l.data_type()),Expr::Case(case) => {@@ -276,7 +276,7 @@ impl ExprSchemable for Expr {|| high.nullable(input_schema)?),Expr::Column(c) => input_schema.nullable(c),- Expr::OuterReferenceColumn(_, _) => Ok(true),+ Expr::OuterReferenceColumn(field, _) => Ok(field.is_nullable()),Expr::Literal(value, _) => Ok(value.is_null()),Expr::Case(case) => {// This expression is nullable if any of the input expressions are nullable@@ -457,8 +457,8 @@ impl ExprSchemable for Expr {}Expr::Negative(expr) => expr.to_field(schema).map(|(_, f)| f),Expr::Column(c) => schema.field_from_column(c).map(|f| Arc::new(f.clone())),- Expr::OuterReferenceColumn(ty, _) => {- Ok(Arc::new(Field::new(&schema_name, ty.clone(), true)))+ Expr::OuterReferenceColumn(field, _) => {+ Ok(Arc::new(field.as_ref().clone().with_name(&schema_name)))}Expr::ScalarVariable(ty, _) => {Ok(Arc::new(Field::new(&schema_name, ty.clone(), true)))@@ -777,7 +777,7 @@ pub fn cast_subquery(subquery: Subquery, cast_to_type: &DataType) -> Result<Subq#[cfg(test)]mod tests {use super::*;- use crate::{col, lit};+ use crate::{col, lit, out_ref_col_with_metadata};use datafusion_common::{internal_err, DFSchema, HashMap, ScalarValue};@@ -911,6 +911,14 @@ mod tests {// verify to_field method populates metadataassert_eq!(meta, expr.metadata(&schema).unwrap());++ // outer ref constructed by `out_ref_col_with_metadata` should be metadata-preserving+ let outer_ref = out_ref_col_with_metadata(+ DataType::Int32,+ meta.to_hashmap(),+ Column::from_name("foo"),+ );+ assert_eq!(meta, outer_ref.metadata(&schema).unwrap());}#[derive(Debug)]diff --git a/datafusion/sql/src/expr/identifier.rs b/datafusion/sql/src/expr/identifier.rsindex 434ac50bce..46b0aae756 100644--- a/datafusion/sql/src/expr/identifier.rs+++ b/datafusion/sql/src/expr/identifier.rs@@ -23,6 +23,7 @@ use datafusion_common::{use datafusion_expr::planner::PlannerResult;use datafusion_expr::{Case, Expr};use sqlparser::ast::{CaseWhen, Expr as SQLExpr, Ident};+use std::sync::Arc;use crate::planner::{ContextProvider, PlannerContext, SqlToRel};use datafusion_expr::UNNAMED_TABLE;@@ -75,7 +76,7 @@ impl<S: ContextProvider> SqlToRel<'_, S> {{// Found an exact match on a qualified name in the outer plan schema, so this is an outer reference columnreturn Ok(Expr::OuterReferenceColumn(- field.data_type().clone(),+ Arc::new(field.clone()),Column::from((qualifier, field)),));}@@ -182,7 +183,7 @@ impl<S: ContextProvider> SqlToRel<'_, S> {Some((field, qualifier, _nested_names)) => {// Found an exact match on a qualified name in the outer plan schema, so this is an outer reference columnOk(Expr::OuterReferenceColumn(- field.data_type().clone(),+ Arc::new(field.clone()),Column::from((qualifier, field)),))}diff --git a/datafusion/sqllogictest/test_files/joins.slt b/datafusion/sqllogictest/test_files/joins.sltindex ad21bdac6d..c24b0777cc 100644--- a/datafusion/sqllogictest/test_files/joins.slt+++ b/datafusion/sqllogictest/test_files/joins.slt@@ -4034,12 +4034,12 @@ logical_plan09)------------Unnest: lists[__unnest_placeholder(generate_series(Int64(1),outer_ref(t1.t1_int)))|depth=1] structs[]10)--------------Projection: generate_series(Int64(1), CAST(outer_ref(t1.t1_int) AS Int64)) AS __unnest_placeholder(generate_series(Int64(1),outer_ref(t1.t1_int)))11)----------------EmptyRelation: rows=1-physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(UInt32, Column { relation: Some(Bare { table: "t1" }), name: "t1_int" })+physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Field { name: "t1_int", data_type: UInt32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, Column { relation: Some(Bare { table: "t1" }), name: "t1_int" })# Test CROSS JOIN LATERAL syntax (execution)# TODO: https://github.com/apache/datafusion/issues/10048-query error DataFusion error: This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn\(UInt32, Column \{ relation: Some\(Bare \{ table: "t1" \}\), name: "t1_int" \}\)+query error DataFusion error: This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn\(Field \{ name: "t1_int", data_type: UInt32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: \{\} \}, Column \{ relation: Some\(Bare \{ table: "t1" \}\), name: "t1_int" \}\)select t1_id, t1_name, i from join_t1 t1 cross join lateral (select * from unnest(generate_series(1, t1_int))) as series(i);@@ -4059,12 +4059,12 @@ logical_plan09)------------Unnest: lists[__unnest_placeholder(generate_series(Int64(1),outer_ref(t2.t1_int)))|depth=1] structs[]10)--------------Projection: generate_series(Int64(1), CAST(outer_ref(t2.t1_int) AS Int64)) AS __unnest_placeholder(generate_series(Int64(1),outer_ref(t2.t1_int)))11)----------------EmptyRelation: rows=1-physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(UInt32, Column { relation: Some(Bare { table: "t2" }), name: "t1_int" })+physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Field { name: "t1_int", data_type: UInt32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, Column { relation: Some(Bare { table: "t2" }), name: "t1_int" })# Test INNER JOIN LATERAL syntax (execution)# TODO: https://github.com/apache/datafusion/issues/10048-query error DataFusion error: This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn\(UInt32, Column \{ relation: Some\(Bare \{ table: "t2" \}\), name: "t1_int" \}\)+query error DataFusion error: This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn\(Field \{ name: "t1_int", data_type: UInt32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: \{\} \}, Column \{ relation: Some\(Bare \{ table: "t2" \}\), name: "t1_int" \}\)select t1_id, t1_name, i from join_t1 t2 inner join lateral (select * from unnest(generate_series(1, t1_int))) as series(i) on(t1_id > i);# Test RIGHT JOIN LATERAL syntax (unsupported)@@ -4669,7 +4669,7 @@ logical_plan05)------Subquery:06)--------Filter: outer_ref(j1.j1_id) < j2.j2_id07)----------TableScan: j2 projection=[j2_string, j2_id]-physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Int32, Column { relation: Some(Bare { table: "j1" }), name: "j1_id" })+physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Field { name: "j1_id", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, Column { relation: Some(Bare { table: "j1" }), name: "j1_id" })query TTexplain SELECT * FROM j1 JOIN (j2 JOIN j3 ON(j2_id = j3_id - 2)) ON(j1_id = j2_id), LATERAL (SELECT * FROM j3 WHERE j3_string = j2_string) as j4@@ -4685,7 +4685,7 @@ logical_plan08)----Subquery:09)------Filter: j3.j3_string = outer_ref(j2.j2_string)10)--------TableScan: j3 projection=[j3_string, j3_id]-physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Utf8View, Column { relation: Some(Bare { table: "j2" }), name: "j2_string" })+physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Field { name: "j2_string", data_type: Utf8View, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, Column { relation: Some(Bare { table: "j2" }), name: "j2_string" })query TTexplain SELECT * FROM j1, LATERAL (SELECT * FROM j1, LATERAL (SELECT * FROM j2 WHERE j1_id = j2_id) as j2) as j2;@@ -4701,7 +4701,7 @@ logical_plan08)----------Subquery:09)------------Filter: outer_ref(j1.j1_id) = j2.j2_id10)--------------TableScan: j2 projection=[j2_string, j2_id]-physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Int32, Column { relation: Some(Bare { table: "j1" }), name: "j1_id" })+physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Field { name: "j1_id", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, Column { relation: Some(Bare { table: "j1" }), name: "j1_id" })query TTexplain SELECT j1_string, j2_string FROM j1 LEFT JOIN LATERAL (SELECT * FROM j2 WHERE j1_id < j2_id) AS j2 ON(true);@@ -4714,7 +4714,7 @@ logical_plan05)------Subquery:06)--------Filter: outer_ref(j1.j1_id) < j2.j2_id07)----------TableScan: j2 projection=[j2_string, j2_id]-physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Int32, Column { relation: Some(Bare { table: "j1" }), name: "j1_id" })+physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Field { name: "j1_id", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, Column { relation: Some(Bare { table: "j1" }), name: "j1_id" })query TTexplain SELECT * FROM j1, (j2 LEFT JOIN LATERAL (SELECT * FROM j3 WHERE j1_id + j2_id = j3_id) AS j3 ON(true));@@ -4728,7 +4728,7 @@ logical_plan06)------Subquery:07)--------Filter: outer_ref(j1.j1_id) + outer_ref(j2.j2_id) = j3.j3_id08)----------TableScan: j3 projection=[j3_string, j3_id]-physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Int32, Column { relation: Some(Bare { table: "j1" }), name: "j1_id" })+physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Field { name: "j1_id", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, Column { relation: Some(Bare { table: "j1" }), name: "j1_id" })query TTexplain SELECT * FROM j1, LATERAL (SELECT 1) AS j2;diff --git a/datafusion/sqllogictest/test_files/unnest.slt b/datafusion/sqllogictest/test_files/unnest.sltindex d955d4c19e..67b3a7cf56 100644--- a/datafusion/sqllogictest/test_files/unnest.slt+++ b/datafusion/sqllogictest/test_files/unnest.slt@@ -863,11 +863,11 @@ select count(*) from (select unnest(range(0, 100000)) id) t inner join (select u# Test implicit LATERAL support for UNNEST# Issue: https://github.com/apache/datafusion/issues/13659# TODO: https://github.com/apache/datafusion/issues/10048-query error DataFusion error: This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn\(List\(Field \{ name: "item", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: \{\} \}\), Column \{ relation: Some\(Bare \{ table: "u" \}\), name: "column1" \}\)+query error DataFusion error: This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn\(Field \{ name: "column1", data_type: List\(Field \{ name: "item", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: \{\} \}\), nullable: true, dict_id: 0, dict_is_ordered: false, metadata: \{\} \}, Column \{ relation: Some\(Bare \{ table: "u" \}\), name: "column1" \}\)select * from unnest_table u, unnest(u.column1);# Test implicit LATERAL support for UNNEST (INNER JOIN)-query error DataFusion error: This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn\(List\(Field \{ name: "item", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: \{\} \}\), Column \{ relation: Some\(Bare \{ table: "u" \}\), name: "column1" \}\)+query error DataFusion error: This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn\(Field \{ name: "column1", data_type: List\(Field \{ name: "item", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: \{\} \}\), nullable: true, dict_id: 0, dict_is_ordered: false, metadata: \{\} \}, Column \{ relation: Some\(Bare \{ table: "u" \}\), name: "column1" \}\)select * from unnest_table u INNER JOIN unnest(u.column1) AS t(column1) ON u.column3 = t.column1;# Test implicit LATERAL planning for UNNEST@@ -883,7 +883,7 @@ logical_plan06)------Unnest: lists[__unnest_placeholder(outer_ref(u.column1))|depth=1] structs[]07)--------Projection: outer_ref(u.column1) AS __unnest_placeholder(outer_ref(u.column1))08)----------EmptyRelation: rows=1-physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(List(Field { name: "item", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), Column { relation: Some(Bare { table: "u" }), name: "column1" })+physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Field { name: "column1", data_type: List(Field { name: "item", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, Column { relation: Some(Bare { table: "u" }), name: "column1" })# Test implicit LATERAL planning for UNNEST (INNER JOIN)query TT@@ -899,7 +899,7 @@ logical_plan07)--------Unnest: lists[__unnest_placeholder(outer_ref(u.column1))|depth=1] structs[]08)----------Projection: outer_ref(u.column1) AS __unnest_placeholder(outer_ref(u.column1))09)------------EmptyRelation: rows=1-physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(List(Field { name: "item", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), Column { relation: Some(Bare { table: "u" }), name: "column1" })+physical_plan_error This feature is not implemented: Physical plan does not support logical expression OuterReferenceColumn(Field { name: "column1", data_type: List(Field { name: "item", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, Column { relation: Some(Bare { table: "u" }), name: "column1" })# uncorrelated EXISTS with unnestquery I