jayzhan211 commented on code in PR #27788:
URL: https://github.com/apache/datafusion/pull/27788#discussion_r4727199000


##########
datafusion/optimizer/src/analyzer/type_coercion.rs:
##########
@@ -1721,11 +1729,48 @@ fn coerce_union_schema_with_schema(
         .iter()
         .enumerate()
         .map(|(i, field)| {
+            let input_fields: Vec<&Field> = inputs
+                .iter()
+                .map(|plan| plan.schema().field(i).as_ref())
+                .collect();
+
+            // Validate extension type compatibility across non-Null inputs.

Review Comment:
   @cyberbeam524 thanks for picking this up! This check also rejects 5 UNION 
shapes that run correctly in 56.0.0, for example `UUID` with a plain 
`FixedSizeBinary(16)` column, or extension metadata that differs only in its 
bytes (#26810, the GeoArrow CRS case). Every broken shape coerces to a storage 
type that no input carried the extension on (`FixedSizeBinary(16)<arrow.uuid>` 
+ `Binary` → `Binary`), so the error can be limited to that. The diff below 
does this. For differing names it reuses `coerced_fields_metadata` (the 
existing helper @tschwarzinger asked about), so UNION follows the same rule as 
CASE and COALESCE.
   
   <details>
   <summary>Per-query results: 56.0.0, this PR, and the diff below</summary>
   
   | Query (UNION ALL unless noted) | 56.0.0 | this PR | diff below |
   |---|---|---|---|
   | `UUID` + plain `FixedSizeBinary(16)` (also UNION, and a table column) | 
rows, `arrow.uuid` kept | error | rows, `arrow.uuid` kept |
   | `arrow.json` on Utf8 + `arrow.json` on Utf8View | rows, kept | error | 
rows, kept |
   | `arrow.json` with metadata `{}` + `{ }` | rows, kept | error | rows, kept |
   | `UUID` + `X'..'` (UNION) | internal error | error | error |
   | `UUID` + `X'..'`; `UUID` + `NULL` + `X'..'` | `arrow.uuid` dropped | error 
| error |
   | `arrow.json` on Utf8 + plain Utf8View | `arrow.json` dropped | error | 
error |
   | `arrow.json` + `arrow.opaque` | relabeled `arrow.opaque` | error | error |
   | tensor `{"shape":[2,5]}` + `{"shape":[5,2]}` | last shape wins | error | 
last shape wins |
   
   </details>
   
   ```diff
   -use datafusion_common::metadata::merge_metadata_for_union;
   +use datafusion_common::metadata::{coerced_fields_metadata, 
merge_metadata_for_union};
   @@
   -/// Returns `true` if two fields have the same extension type (name, 
metadata,
   -/// and underlying storage type).
   -fn extension_types_equal(left: &Field, right: &Field) -> bool {
   -    left.extension_type_name() == right.extension_type_name()
   -        && left.extension_type_metadata() == right.extension_type_metadata()
   -        && left.data_type() == right.data_type()
   +/// Rejects UNION inputs whose extension type cannot be kept on the coerced
   +/// storage type `coerced`.
   +///
   +/// TODO(#27383): replace with an extension-aware common type rule.
   +fn check_union_extension_type(
   +    name: &str,
   +    fields: &[&Field],
   +    coerced: &DataType,
   +) -> Result<()> {
   +    // Same rule as CASE and COALESCE: differing extension names are an 
error,
   +    // differing extension metadata bytes are not (#26810).
   +    coerced_fields_metadata(fields.iter().copied())?;
   +    // NULL inputs are skipped, as in `coerced_fields_metadata`.
   +    let Some(extension) = fields
   +        .iter()
   +        .filter(|f| !f.data_type().is_null())
   +        .find_map(|f| f.extension_type_name())
   +    else {
   +        return Ok(());
   +    };
   +    // The merged metadata is only valid on a storage type that an input
   +    // already carried this extension type on.
   +    let keeps_storage = fields
   +        .iter()
   +        .any(|f| f.extension_type_name() == Some(extension) && 
f.data_type() == coerced);
   +    if !keeps_storage {
   +        return plan_err!(
   +            "UNION types cannot be unified for column '{name}': extension 
type \
   +            '{extension}' cannot be stored as {coerced}"
   +        );
   +    }
   +    Ok(())
    }
   @@ fn coerce_union_schema_with_schema(
   -            // Validate extension type compatibility across non-Null inputs.
   -            // ... (the whole `if let Some(ext_field) = ...` block)
   -            let datatype = coerce_union_type(input_fields)?;
   +            let datatype = coerce_union_type(input_fields.iter().copied())?;
   +            check_union_extension_type(field.name(), &input_fields, 
&datatype)?;
   @@ fn test_coerce_union_incompatible_extension_type
   -                vec![Field::new("id", DataType::FixedSizeBinary(16), 
false)].into(),
   +                vec![Field::new("id", DataType::Binary, false)].into(),
   ```
   
   With this applied, `cargo test -p datafusion-optimizer` and 
`sql_extension_types.slt` (with the test change suggested on the `.slt` file) 
pass, and clippy is clean.



##########
datafusion/sqllogictest/test_files/sql_extension_types.slt:
##########
@@ -192,3 +192,84 @@ 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
+
+# UNION and UNION ALL between UUID and a bare Binary literal return a planning 
error
+statement error UNION types cannot be unified for column 'id'
+SELECT id FROM t
+UNION
+SELECT X'00010203040506070809000102030507';
+
+statement error UNION types cannot be unified for column 'id'
+SELECT id FROM t
+UNION ALL
+SELECT X'00010203040506070809000102030507';
+
+# Same extension name but different storage type (FixedSizeBinary(16) vs 
Binary) also fails
+statement error UNION types cannot be unified for column 'id'
+SELECT id FROM t
+UNION
+SELECT with_metadata(
+  X'00010203040506070809000102030507',
+  'ARROW:extension:name',
+  'arrow.uuid'
+);
+
+# Same extension name and storage type but different extension payload also 
fails
+# (e.g. arrow.fixed_shape_tensor with incompatible shapes [2, 5] vs [5, 2])
+statement error UNION types cannot be unified for column 'tensor'
+SELECT with_metadata(
+  with_metadata(
+    arrow_cast([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'FixedSizeList(10, Int64)'),
+    'ARROW:extension:name',
+    'arrow.fixed_shape_tensor'
+  ),
+  'ARROW:extension:metadata',
+  '{"shape":[2,5]}'
+) AS tensor
+UNION
+SELECT with_metadata(
+  with_metadata(
+    arrow_cast([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'FixedSizeList(10, Int64)'),
+    'ARROW:extension:name',
+    'arrow.fixed_shape_tensor'
+  ),
+  'ARROW:extension:metadata',
+  '{"shape":[5,2]}'
+) AS tensor;

Review Comment:
   With the narrower check, these two tests no longer error. `arrow.uuid` on 
`Binary` is already an invalid field before the UNION. The tensor shapes can't 
be told apart from the whitespace-only difference in #26810 without parsing the 
metadata, so that case can wait for the registry from #27383. This replaces 
them with one test per side of the new rule, all run locally:
   
   ```suggestion
   # 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
   
   # Utf8View never carried arrow.json in any input, so the result would drop it
   statement error UNION types cannot be unified for column 'j'
   SELECT with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json') AS j
   UNION ALL
   SELECT arrow_cast('{"b":2}', 'Utf8View');
   
   # Different extension names are an error, as in CASE and COALESCE
   statement error Cannot merge field metadata with differing values of 
'ARROW:extension:name'
   SELECT with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json') AS j
   UNION ALL
   SELECT with_metadata('x', 'ARROW:extension:name', 'arrow.opaque');
   
   # A NULL input's metadata does not pick the extension type
   query T
   SELECT arrow_metadata(j, 'ARROW:extension:name') FROM (
     SELECT with_metadata(NULL, 'ARROW:extension:name', 'arrow.opaque') AS j
     UNION ALL
     SELECT with_metadata('x', 'ARROW:extension:name', 'arrow.json')
   ) WHERE j IS NOT NULL;
   ----
   arrow.json
   ```



-- 
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]

Reply via email to