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


##########
datafusion/optimizer/src/analyzer/type_coercion.rs:
##########
@@ -1649,6 +1649,40 @@ fn coerce_case_expression(
     Ok(Case::new(case_expr, when_then, else_expr))
 }
 
+/// 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(

Review Comment:
   @cyberbeam524 thanks for applying the change, and sorry: I missed this in my 
last review. Both errors in this check reject queries that return correct rows 
in 56.0.0. For example, `SELECT count(*) FROM (SELECT id FROM t UNION ALL 
SELECT X'0001')` returns 2 there, and `INSERT INTO t SELECT id FROM t UNION ALL 
SELECT X'..'` stores the right rows; this PR errors on both. The internal error 
comes from the logical UNION schema keeping extension keys that the physical 
union doesn't have, because coercion casts every input whose type differs and 
the cast drops them. Taking those keys only from inputs already stored as the 
coerced type fixes it with no new error. The diff below does that, and the two 
`.slt` suggestions update the tests. Since `UNION ALL` still returns `Binary` 
until #27383 can coerce the literal to `UUID`, could the description say `Part 
of #26915` instead of `Closes`?
   
   <details>
   <summary>Per-query results: 56.0.0, this PR, and the diff below</summary>
   
   | Query | 56.0.0 | this PR | diff below |
   |---|---|---|---|
   | `count(*)` over `UUID UNION ALL X'..'` | 2 | error | 2 |
   | `INSERT INTO <UUID or BYTEA table>` from `UUID UNION ALL X'..'` | rows 
stored | error | rows stored |
   | `UUID UNION X'..'` | internal error | error | rows, `Binary` |
   | `UUID UNION ALL BY NAME X'..'`; `Dictionary(Int32, FixedSizeBinary(16))` 
input; `arrow.json` + plain `LargeUtf8` | rows | error | rows |
   | `count(*)` over `arrow.json UNION ALL arrow.opaque` | 2 | error | 2 |
   | `arrow.json` with metadata `{}` on Utf8 `UNION` `arrow.json` on Utf8View | 
internal error | internal error | rows |
   | all-NULL inputs with an extension, `UNION` | rows | rows | rows |
   
   With the diff, the full sqllogictest suite (309 files) and `cargo test -p 
datafusion-optimizer` pass, and clippy and `cargo doc` are clean.
   </details>
   
   <details>
   <summary>Diff (also adds `arrow-schema = { workspace = true }` to 
datafusion/optimizer/Cargo.toml)</summary>
   
   ```diff
   +use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, 
EXTENSION_TYPE_NAME_KEY};
   -use datafusion_common::metadata::{coerced_fields_metadata, 
merge_metadata_for_union};
   +use datafusion_common::metadata::merge_metadata_for_union;
   @@
   -/// Rejects UNION inputs whose extension type cannot be kept on the coerced
   -/// ... (remove `check_union_extension_type` entirely)
   @@ pub fn coerce_union_schema
    /// - **Metadata**: Later inputs take precedence for same keys 
(HashMap::extend semantics)
   +/// - **Extension type**: Taken only from inputs already stored as the 
coerced type,
   +///   since coercion casts the others and a cast drops the extension type
   @@ fn coerce_union_schema_with_schema(
                let datatype = coerce_union_type(input_fields.iter().copied())?;
   -            check_union_extension_type(field.name(), &input_fields, 
&datatype)?;
                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);
   ```
   
   The test below replaces `test_coerce_union_incompatible_extension_type`. It 
checks the NULL-input filter, which the `.slt` tests can't see because 
optimizer rules recompute the UNION schema after type coercion:
   
   ```rs
   #[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);
   
       // A NULL input's extension type does not decide the result
       let schema = coerce_union_schema(&[
           input(DataType::Null, Some("arrow.opaque"))?,
           input(Utf8, Some("arrow.json"))?,
       ])?;
       assert_eq!(schema.field(0).extension_type_name(), Some("arrow.json"));
       Ok(())
   }
   ```
   </details>



##########
datafusion/sqllogictest/test_files/sql_extension_types.slt:
##########
@@ -192,3 +192,106 @@ 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';

Review Comment:
   With the change suggested on `type_coercion.rs`, these return `Binary` rows, 
as in 56.0.0, and `UNION` no longer hits the internal error:
   
   ```suggestion
   # 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
   ```



##########
datafusion/optimizer/src/analyzer/type_coercion.rs:
##########
@@ -1721,11 +1756,13 @@ fn coerce_union_schema_with_schema(
         .iter()
         .enumerate()
         .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();

Review Comment:
   Optional cleanup: this comment from `main` was dropped, but the reason it 
gives still explains why the types come from `inputs` and not from the stored 
schema:
   
   ```suggestion
               // The stored schema may already contain an inferred common 
type. Feeding
               // it back into coercion can change the result, notably for 
dictionaries.
               let input_fields: Vec<&Field> = inputs
                   .iter()
                   .map(|plan| plan.schema().field(i).as_ref())
                   .collect();
   ```



##########
datafusion/sqllogictest/test_files/sql_extension_types.slt:
##########
@@ -192,3 +192,106 @@ 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';
+
+# 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');

Review Comment:
   These replace the two error tests. Each one fails if a condition in the 
suggested loop is removed: the first catches first-wins instead of last-wins, 
the third keeping metadata from a cast input, and the last skipping all-NULL 
inputs.
   
   ```suggestion
   # 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
   ```



##########
datafusion/sqllogictest/test_files/sql_extension_types.slt:
##########
@@ -192,3 +192,106 @@ 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';
+
+# 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
+
+# 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;

Review Comment:
   Optional cleanup: the file is missing its trailing newline.



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