diff --git a/Cargo.lock b/Cargo.lock index 336d69d12547a..192c0195794af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2465,6 +2465,7 @@ name = "datafusion-optimizer" version = "57.0.0-dev" dependencies = [ "arrow", + "arrow-schema", "async-trait", "chrono", "criterion", diff --git a/datafusion/optimizer/Cargo.toml b/datafusion/optimizer/Cargo.toml index 55b1486a405b4..7df8013cdc9b0 100644 --- a/datafusion/optimizer/Cargo.toml +++ b/datafusion/optimizer/Cargo.toml @@ -40,6 +40,7 @@ recursive_protection = ["dep:recursive"] # traits). [dependencies] arrow = { workspace = true } +arrow-schema = { workspace = true } chrono = { workspace = true } datafusion-common = { workspace = true, default-features = true } datafusion-expr = { workspace = true } diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index faf7531496291..86902765ded90 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -14,6 +14,7 @@ use crate::utils::{NamePreserver, merge_into_schema}; use arrow::datatypes::{DataType, Field, IntervalUnit, Schema, TimeUnit}; use arrow::temporal_conversions::SECONDS_IN_DAY; +use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY}; use datafusion_common::config::ConfigOptions; use datafusion_common::metadata::merge_metadata_for_union; use datafusion_common::tree_node::{ @@ -1661,7 +1662,10 @@ fn coerce_case_expression( /// /// **Schema-level metadata merging**: Later schemas take precedence for duplicate keys. /// -/// **Field-level metadata merging**: Later fields take precedence for duplicate metadata keys. +/// **Field-level metadata merging**: Later fields take precedence for duplicate metadata keys, +/// except the extension type keys (`ARROW:extension:name` and `ARROW:extension:metadata`): +/// those come only from inputs whose type already equals the coerced type, because +/// coercion casts the other inputs and the cast drops their extension type. /// /// **Type coercion precedence**: The coerced type is determined by iteratively applying /// `type_union_coercion()` between the accumulated type and each new input's type. The @@ -1689,13 +1693,15 @@ fn coerce_case_expression( /// **Precedence Summary**: /// - **Datatypes**: Folded in input order using `type_union_coercion()` /// - **Nullability**: Later inputs can add nullability but cannot remove it (logical OR) -/// - **Metadata**: Later inputs take precedence for same keys (HashMap::extend semantics) +/// - **Metadata**: Later inputs take precedence for same keys (HashMap::extend semantics), +/// except extension type keys, which come only from inputs already of the coerced type pub fn coerce_union_schema(inputs: &[Arc]) -> Result { let Some(first) = inputs.first() else { return plan_err!("UNION requires at least one input"); }; coerce_union_schema_with_schema(inputs, first.schema()) } + fn coerce_union_schema_with_schema( inputs: &[Arc], base_schema: &DFSchemaRef, @@ -1723,17 +1729,35 @@ fn coerce_union_schema_with_schema( .map(|(i, field)| { // The stored schema may already contain an inferred common type. Feeding // it back into coercion can change the result, notably for dictionaries. - let datatype = coerce_union_type( - inputs.iter().map(|plan| plan.schema().field(i).as_ref()), - )?; + let input_fields: Vec<&Field> = inputs + .iter() + .map(|plan| plan.schema().field(i).as_ref()) + .collect(); + + let datatype = coerce_union_type(input_fields.iter().copied())?; let nullable = field.is_nullable() || inputs .iter() .any(|plan| plan.schema().field(i).is_nullable()); - let mut field = Field::new(field.name().clone(), datatype, nullable); - field.set_metadata(merge_metadata_for_union( + let mut metadata = merge_metadata_for_union( all_schemas.iter().map(|schema| schema.field(i).metadata()), - )); + ); + // Coercion casts each input not stored as `datatype`, and the cast + // drops its extension type, so only the other inputs can supply it. + // Anything else differs from the physical union's schema (#26915). + for key in [EXTENSION_TYPE_NAME_KEY, EXTENSION_TYPE_METADATA_KEY] { + metadata.remove(key); + if let Some(value) = input_fields + .iter() + .rev() + .filter(|f| f.data_type() == &datatype) + .find_map(|f| f.metadata().get(key)) + { + metadata.insert(key, value.clone()); + } + } + let mut field = Field::new(field.name().clone(), datatype, nullable); + field.set_metadata(metadata); Ok((None, field.into())) }) .collect::>>()?; @@ -2012,6 +2036,47 @@ mod test { ) } + #[test] + fn coerce_union_schema_extension_type() -> Result<()> { + use super::coerce_union_schema; + use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY; + let input = |data_type: DataType, extension: Option<&str>| { + let mut field = Field::new("c", data_type, true); + if let Some(extension) = extension { + field = field.with_metadata(std::collections::HashMap::from([( + EXTENSION_TYPE_NAME_KEY.to_string(), + extension.to_string(), + )])); + } + DFSchema::from_unqualified_fields( + vec![field].into(), + std::collections::HashMap::new(), + ) + .map(|schema| { + Arc::new(LogicalPlan::EmptyRelation(EmptyRelation { + produce_one_row: false, + schema: Arc::new(schema), + })) + }) + }; + + // No input stores arrow.uuid as Binary, so the result drops it + let schema = coerce_union_schema(&[ + input(DataType::FixedSizeBinary(16), Some("arrow.uuid"))?, + input(DataType::Binary, None)?, + ])?; + assert_eq!(schema.field(0).data_type(), &DataType::Binary); + assert_eq!(schema.field(0).extension_type_name(), None); + + // Inputs already stored as the coerced type keep their extension type + let schema = coerce_union_schema(&[ + input(DataType::FixedSizeBinary(16), Some("arrow.uuid"))?, + input(DataType::FixedSizeBinary(16), Some("arrow.uuid"))?, + ])?; + assert_eq!(schema.field(0).extension_type_name(), Some("arrow.uuid")); + Ok(()) + } + #[test] fn merge_into_resolves_and_coerces_target_and_source_columns() -> Result<()> { use datafusion_expr::dml::{ diff --git a/datafusion/sqllogictest/test_files/sql_extension_types.slt b/datafusion/sqllogictest/test_files/sql_extension_types.slt index 957f3dedfc09e..2d725d8f1a7c0 100644 --- a/datafusion/sqllogictest/test_files/sql_extension_types.slt +++ b/datafusion/sqllogictest/test_files/sql_extension_types.slt @@ -192,3 +192,138 @@ INSERT INTO t1 VALUES (NULL); statement ok DROP TABLE t1; + +statement ok +CREATE TABLE t (id UUID); + +statement ok +INSERT INTO t VALUES + (CAST(arrow_cast(X'00010203040506070809000102030506', 'FixedSizeBinary(16)') AS UUID)); + +# Verify t.id actually has arrow.uuid metadata +query T +SELECT arrow_metadata(id, 'ARROW:extension:name') FROM t; +---- +arrow.uuid + +# UUID with a bare Binary literal is Binary, as in 56.0.0, until #27383 can +# coerce the literal to UUID; UNION no longer fails with an internal error +query ?TT +SELECT id, arrow_typeof(id), arrow_metadata(id, 'ARROW:extension:name') FROM ( + SELECT id FROM t + UNION + SELECT X'00010203040506070809000102030507' +) ORDER BY id; +---- +00010203040506070809000102030506 Binary NULL +00010203040506070809000102030507 Binary NULL + +query ?TT +SELECT id, arrow_typeof(id), arrow_metadata(id, 'ARROW:extension:name') FROM ( + SELECT id FROM t + UNION ALL + SELECT X'00010203040506070809000102030507' +) ORDER BY id; +---- +00010203040506070809000102030506 Binary NULL +00010203040506070809000102030507 Binary NULL + +# A plain FixedSizeBinary(16) keeps the UUID type, as in 56.0.0 +query ?T +SELECT id, arrow_metadata(id, 'ARROW:extension:name') FROM ( + SELECT id FROM t + UNION ALL + SELECT arrow_cast(X'00010203040506070809000102030507', 'FixedSizeBinary(16)') +) ORDER BY id; +---- +00010203040506070809000102030506 arrow.uuid +00010203040506070809000102030507 arrow.uuid + +# The coerced storage type (Utf8View) already carries arrow.json in one input +query TT +SELECT j, arrow_metadata(j, 'ARROW:extension:name') FROM ( + SELECT with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json') AS j + UNION ALL + SELECT with_metadata(arrow_cast('{"b":2}', 'Utf8View'), 'ARROW:extension:name', 'arrow.json') +) ORDER BY j; +---- +{"a":1} arrow.json +{"b":2} arrow.json + +# Extension metadata that differs only in its bytes is not an error (#26810) +query T +SELECT arrow_metadata(j, 'ARROW:extension:name') FROM ( + SELECT with_metadata(with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json'), 'ARROW:extension:metadata', '{}') AS j + UNION ALL + SELECT with_metadata(with_metadata('{"b":2}', 'ARROW:extension:name', 'arrow.json'), 'ARROW:extension:metadata', '{ }') +); +---- +arrow.json +arrow.json + +# As in the physical union, the last input's extension metadata wins +query T +SELECT arrow_metadata(j, 'ARROW:extension:metadata') FROM ( + SELECT with_metadata(with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json'), 'ARROW:extension:metadata', '{}') AS j + UNION + SELECT with_metadata(with_metadata('{"b":2}', 'ARROW:extension:name', 'arrow.json'), 'ARROW:extension:metadata', '{ }') +); +---- +{ } +{ } + +# Utf8View never carried arrow.json in any input, so the result drops it +query TT +SELECT j, arrow_metadata(j, 'ARROW:extension:name') FROM ( + SELECT with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json') AS j + UNION ALL + SELECT arrow_cast('{"b":2}', 'Utf8View') +) ORDER BY j; +---- +{"a":1} NULL +{"b":2} NULL + +# Extension metadata of an input cast to Utf8View is not kept +query TT +SELECT j, arrow_metadata(j, 'ARROW:extension:metadata') FROM ( + SELECT with_metadata(with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json'), 'ARROW:extension:metadata', '{}') AS j + UNION + SELECT with_metadata(arrow_cast('{"b":2}', 'Utf8View'), 'ARROW:extension:name', 'arrow.json') +) ORDER BY j; +---- +{"a":1} NULL +{"b":2} NULL + +# NULL inputs keep their extension type when every input is NULL +query T +SELECT arrow_metadata(j, 'ARROW:extension:name') FROM ( + SELECT with_metadata(NULL, 'ARROW:extension:name', 'arrow.opaque') AS j + UNION + SELECT with_metadata(NULL, 'ARROW:extension:name', 'arrow.opaque') +); +---- +arrow.opaque + +# NULL branch does not force incompatibility and preserves extension metadata +query T +SELECT arrow_metadata(id, 'ARROW:extension:name') FROM ( + SELECT id FROM t + UNION ALL + SELECT NULL +) LIMIT 1; +---- +arrow.uuid + +# UNION between two UUID columns works and preserves arrow.uuid +query T +SELECT arrow_metadata(id, 'ARROW:extension:name') FROM ( + SELECT id FROM t + UNION + SELECT CAST(arrow_cast(X'00010203040506070809000102030507', 'FixedSizeBinary(16)') AS UUID) +); +---- +arrow.uuid +arrow.uuid + +statement ok +DROP TABLE t;