@@ -46,7 +46,7 @@ use crate::statistics::{ChildStats, StatisticsArgs};
4646use crate :: stream:: ObservedStream ;
4747use crate :: { ChildrenPropertiesMode , ReplaceChildrenOptions , validate_child_count} ;
4848
49- use arrow:: datatypes:: { Field , Schema , SchemaRef } ;
49+ use arrow:: datatypes:: { Schema , SchemaRef } ;
5050use arrow:: record_batch:: RecordBatch ;
5151use datafusion_common:: config:: ConfigOptions ;
5252use datafusion_common:: stats:: NdvFallback ;
@@ -918,8 +918,8 @@ fn union_schema(inputs: &[Arc<dyn ExecutionPlan>]) -> Result<SchemaRef> {
918918 let first_schema = inputs[ 0 ] . schema ( ) ;
919919
920920 // Fast path: when every input already shares the first input's schema, the
921- // field-by-field metadata/nullability merge below is redundant work that
922- // scales as O(n^2 * fields). This is common in practice: unions built from
921+ // field-by-field metadata/nullability merge below is redundant work.
922+ // This is common in practice: unions built from
923923 // repartitioned copies of the same plan (e.g. observed in InfluxDB) hand us
924924 // children that all carry the exact same schema. A pointer-equality check
925925 // catches the shared-`Arc` case for free, and a content `==` comparison
@@ -951,31 +951,29 @@ fn union_schema(inputs: &[Arc<dyn ExecutionPlan>]) -> Result<SchemaRef> {
951951 // which also uses the left side names.
952952 let base_field = first_schema. field ( i) . clone ( ) ;
953953
954- // Coerce metadata and nullability across all inputs
955-
956- inputs
954+ // Select the first nullable field, or the first field if none are
955+ // nullable, before merging metadata. Otherwise, each non-nullable
956+ // candidate would repeat the full metadata merge.
957+ let ( input_idx, input) = inputs
957958 . iter ( )
958959 . enumerate ( )
959- . map ( |( input_idx, input) | {
960- let field = input. schema ( ) . field ( i) . clone ( ) ;
961- let mut metadata = field. metadata ( ) . clone ( ) ;
962-
963- let other_metadatas = inputs
964- . iter ( )
965- . enumerate ( )
966- . filter ( |( other_idx, _) | * other_idx != input_idx)
967- . flat_map ( |( _, other_input) | {
968- other_input. schema ( ) . field ( i) . metadata ( ) . clone ( ) . into_iter ( )
969- } ) ;
970-
971- metadata. extend ( other_metadatas) ;
972- field. with_metadata ( metadata)
973- } )
974- . find_or_first ( Field :: is_nullable)
975- // We can unwrap this because if inputs was empty, this would've already panic'ed when we
976- // indexed into inputs[0].
977- . unwrap ( )
978- . with_name ( base_field. name ( ) )
960+ . find_or_first ( |( _, input) | input. schema ( ) . field ( i) . is_nullable ( ) )
961+ // Empty inputs are rejected above.
962+ . unwrap ( ) ;
963+ let field = input. schema ( ) . field ( i) . clone ( ) ;
964+ let mut metadata = field. metadata ( ) . clone ( ) ;
965+
966+ // Preserve precedence: the selected field's metadata comes first,
967+ // followed by the other inputs in their original order.
968+ let other_metadatas = inputs
969+ . iter ( )
970+ . enumerate ( )
971+ . filter ( |( other_idx, _) | * other_idx != input_idx)
972+ . flat_map ( |( _, other_input) | {
973+ other_input. schema ( ) . field ( i) . metadata ( ) . clone ( ) . into_iter ( )
974+ } ) ;
975+ metadata. extend ( other_metadatas) ;
976+ field. with_metadata ( metadata) . with_name ( base_field. name ( ) )
979977 } )
980978 . collect :: < Vec < _ > > ( ) ;
981979
@@ -1067,7 +1065,7 @@ mod tests {
10671065 use crate :: test:: { self , TestMemoryExec } ;
10681066
10691067 use arrow:: compute:: SortOptions ;
1070- use arrow:: datatypes:: DataType ;
1068+ use arrow:: datatypes:: { DataType , Field } ;
10711069 use datafusion_common:: SplitPoint ;
10721070 use datafusion_common:: stats:: Precision ;
10731071 use datafusion_common:: { ColumnStatistics , ScalarValue } ;
@@ -1741,6 +1739,84 @@ mod tests {
17411739 Ok ( ( ) )
17421740 }
17431741
1742+ #[ tokio:: test]
1743+ async fn test_union_schema_metadata_and_nullability ( ) -> Result < ( ) > {
1744+ use arrow:: array:: Int32Array ;
1745+
1746+ // Field metadata from the selected field is merged first, followed by
1747+ // the other inputs in order. Schema metadata always follows input order.
1748+ for ( nullability, expected_field_value) in [
1749+ ( [ false , false , false ] , "input2" ) ,
1750+ ( [ true , false , false ] , "input2" ) ,
1751+ ( [ false , true , false ] , "input2" ) ,
1752+ ( [ false , false , true ] , "input1" ) ,
1753+ ( [ true , true , true ] , "input2" ) ,
1754+ ] {
1755+ let inputs = nullability
1756+ . iter ( )
1757+ . enumerate ( )
1758+ . map ( |( i, & nullable) | {
1759+ let metadata = std:: collections:: HashMap :: from ( [
1760+ ( "shared" . to_owned ( ) , format ! ( "input{i}" ) ) ,
1761+ ( format ! ( "only{i}" ) , "kept" . to_owned ( ) ) ,
1762+ ] ) ;
1763+ let field =
1764+ Field :: new ( format ! ( "value{i}" ) , DataType :: Int32 , nullable)
1765+ . with_metadata ( metadata. clone ( ) ) ;
1766+ let schema =
1767+ Arc :: new ( Schema :: new_with_metadata ( vec ! [ field] , metadata) ) ;
1768+ let batch = RecordBatch :: try_new (
1769+ Arc :: clone ( & schema) ,
1770+ vec ! [ Arc :: new( Int32Array :: from( vec![ i as i32 ] ) ) ] ,
1771+ ) ?;
1772+ let input: Arc < dyn ExecutionPlan > =
1773+ TestMemoryExec :: try_new_exec ( & [ vec ! [ batch] ] , schema, None ) ?;
1774+ Ok ( input)
1775+ } )
1776+ . collect :: < Result < Vec < _ > > > ( ) ?;
1777+
1778+ let expected_metadata = std:: collections:: HashMap :: from ( [
1779+ ( "shared" . to_owned ( ) , expected_field_value. to_owned ( ) ) ,
1780+ ( "only0" . to_owned ( ) , "kept" . to_owned ( ) ) ,
1781+ ( "only1" . to_owned ( ) , "kept" . to_owned ( ) ) ,
1782+ ( "only2" . to_owned ( ) , "kept" . to_owned ( ) ) ,
1783+ ] ) ;
1784+ let mut expected_schema_metadata = expected_metadata. clone ( ) ;
1785+ expected_schema_metadata. insert ( "shared" . to_owned ( ) , "input2" . to_owned ( ) ) ;
1786+ let expected_schema = Arc :: new ( Schema :: new_with_metadata (
1787+ vec ! [
1788+ Field :: new( "value0" , DataType :: Int32 , nullability. contains( & true ) )
1789+ . with_metadata( expected_metadata) ,
1790+ ] ,
1791+ expected_schema_metadata,
1792+ ) ) ;
1793+
1794+ let union = UnionExec :: try_new ( inputs) ?;
1795+ assert_eq ! ( union . schema( ) , expected_schema, "{nullability:?}" ) ;
1796+ let batches = collect ( union, Arc :: new ( TaskContext :: default ( ) ) ) . await ?;
1797+ datafusion_common:: assert_batches_sorted_eq!(
1798+ [
1799+ "+--------+" ,
1800+ "| value0 |" ,
1801+ "+--------+" ,
1802+ "| 0 |" ,
1803+ "| 1 |" ,
1804+ "| 2 |" ,
1805+ "+--------+"
1806+ ] ,
1807+ & batches
1808+ ) ;
1809+ for batch in batches {
1810+ assert_eq ! (
1811+ batch. schema( ) . fields( ) ,
1812+ expected_schema. fields( ) ,
1813+ "{nullability:?}"
1814+ ) ;
1815+ }
1816+ }
1817+ Ok ( ( ) )
1818+ }
1819+
17441820 #[ test]
17451821 fn test_union_schema_mismatch ( ) {
17461822 // Test that UnionExec properly rejects inputs with different field counts
0 commit comments