gstvg commented on code in PR #14687:
URL: https://github.com/apache/datafusion/pull/14687#discussion_r1958697188


##########
datafusion/functions/src/core/union_tag.rs:
##########
@@ -0,0 +1,223 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use arrow::array::{Array, AsArray, DictionaryArray, Int8Array, StringArray};
+use arrow::datatypes::DataType;
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_datafusion_err, exec_err, Result, ScalarValue};
+use datafusion_doc::Documentation;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
+use datafusion_expr::{ScalarUDFImpl, Signature, Volatility};
+use datafusion_macros::user_doc;
+use std::sync::Arc;
+
+#[user_doc(
+    doc_section(label = "Union Functions"),
+    description = "Returns the name of the currently selected field in the 
union",
+    syntax_example = "union_tag(union_expression)",
+    sql_example = r#"```sql
+❯ select union_column, union_tag(union_column) from table_with_union;
++--------------+-------------------------+
+| union_column | union_tag(union_column) |
++--------------+-------------------------+
+| {a=1}        | a                       |
+| {b=3.0}      | b                       |
+| {a=4}        | a                       |
+| {b=}         | b                       |
+| {a=}         | a                       |
++--------------+-------------------------+
+```"#,
+    standard_argument(name = "union", prefix = "Union")
+)]
+#[derive(Debug)]
+pub struct UnionTagFunc {
+    signature: Signature,
+}
+
+impl Default for UnionTagFunc {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl UnionTagFunc {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::any(1, Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for UnionTagFunc {
+    fn as_any(&self) -> &dyn std::any::Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "union_tag"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _: &[DataType]) -> Result<DataType> {
+        Ok(DataType::Dictionary(
+            Box::new(DataType::Int8),
+            Box::new(DataType::Utf8),
+        ))
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let [union_] = take_function_args("union_tag", args.args)?;
+
+        match union_ {
+            ColumnarValue::Array(array)
+                if matches!(array.data_type(), DataType::Union(_, _)) =>
+            {
+                let union_array = array.as_union();
+
+                let keys = Int8Array::try_new(union_array.type_ids().clone(), 
None)?;
+
+                let fields = match union_array.data_type() {
+                    DataType::Union(fields, _) => fields,
+                    _ => unreachable!(),
+                };
+
+                // Union fields type IDs only constraints are being unique and 
in the 0..128 range:
+                // They may not start at 0, be sequential, or even contiguous.
+                // Therefore, we allocate a values vector with a length equal 
to the highest type ID plus one,
+                // ensuring that each field's name can be placed at the index 
corresponding to its type ID.

Review Comment:
   The union column used on the sqllogictests contains a single field with type 
id 3, so this is put to the test
   
https://github.com/apache/datafusion/blob/e4b78c7ed40c248cfc9596d53f1813b62c668249/datafusion/sqllogictest/src/test_context.rs#L411-L430
   
https://github.com/apache/datafusion/blob/e4b78c7ed40c248cfc9596d53f1813b62c668249/datafusion/sqllogictest/src/test_context.rs#L117-L120



-- 
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: github-unsubscr...@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org
For additional commands, e-mail: github-h...@datafusion.apache.org

Reply via email to