-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add union_tag scalar function #14687
Open
gstvg
wants to merge
1
commit into
apache:main
Choose a base branch
from
gstvg:union_tag
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+273
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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. | ||
let values_len = fields | ||
.iter() | ||
.map(|(type_id, _)| type_id + 1) | ||
.max() | ||
.unwrap_or_default() as usize; | ||
|
||
let mut values = vec![""; values_len]; | ||
|
||
for (type_id, field) in fields.iter() { | ||
values[type_id as usize] = field.name().as_str() | ||
} | ||
|
||
let values = Arc::new(StringArray::from(values)); | ||
|
||
// SAFETY: union type_ids are validated to not be smaller than zero. | ||
// values len is the union biggest type id plus one. | ||
// keys is built from the union type_ids, which contains only valid type ids | ||
// therefore, `keys[i] >= values.len() || keys[i] < 0` never occurs | ||
let dict = unsafe { DictionaryArray::new_unchecked(keys, values) }; | ||
|
||
Ok(ColumnarValue::Array(Arc::new(dict))) | ||
} | ||
ColumnarValue::Scalar(ScalarValue::Union(value, fields, _)) => match value { | ||
Some((value_type_id, _)) => fields | ||
.iter() | ||
.find(|(type_id, _)| value_type_id == *type_id) | ||
.map(|(_, field)| { | ||
ColumnarValue::Scalar(ScalarValue::Dictionary( | ||
Box::new(DataType::Int8), | ||
Box::new(field.name().as_str().into()), | ||
)) | ||
}) | ||
.ok_or_else(|| { | ||
exec_datafusion_err!( | ||
"union_tag: union scalar with unknow type_id {value_type_id}" | ||
) | ||
}), | ||
None => Ok(ColumnarValue::Scalar(ScalarValue::try_new_null( | ||
args.return_type, | ||
)?)), | ||
}, | ||
v => exec_err!("union_tag only support unions, got {:?}", v.data_type()), | ||
} | ||
} | ||
|
||
fn documentation(&self) -> Option<&Documentation> { | ||
self.doc() | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::UnionTagFunc; | ||
use arrow::datatypes::{DataType, Field, UnionFields, UnionMode}; | ||
use datafusion_common::ScalarValue; | ||
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl}; | ||
use std::sync::Arc; | ||
|
||
// when it becomes possible to construct union scalars in SQL, this should go to sqllogictests | ||
#[test] | ||
fn union_scalar() { | ||
let fields = [(0, Arc::new(Field::new("a", DataType::UInt32, false)))] | ||
.into_iter() | ||
.collect(); | ||
|
||
let scalar = ScalarValue::Union( | ||
Some((0, Box::new(ScalarValue::UInt32(Some(0))))), | ||
fields, | ||
UnionMode::Dense, | ||
); | ||
|
||
let result = UnionTagFunc::new() | ||
.invoke_with_args(ScalarFunctionArgs { | ||
args: vec![ColumnarValue::Scalar(scalar)], | ||
number_rows: 1, | ||
return_type: &DataType::Dictionary( | ||
Box::new(DataType::Int8), | ||
Box::new(DataType::Utf8), | ||
), | ||
}) | ||
.unwrap(); | ||
|
||
assert_scalar( | ||
result, | ||
ScalarValue::Dictionary(Box::new(DataType::Int8), Box::new("a".into())), | ||
); | ||
} | ||
|
||
#[test] | ||
fn union_scalar_empty() { | ||
let scalar = ScalarValue::Union(None, UnionFields::empty(), UnionMode::Dense); | ||
|
||
let result = UnionTagFunc::new() | ||
.invoke_with_args(ScalarFunctionArgs { | ||
args: vec![ColumnarValue::Scalar(scalar)], | ||
number_rows: 1, | ||
return_type: &DataType::Dictionary( | ||
Box::new(DataType::Int8), | ||
Box::new(DataType::Utf8), | ||
), | ||
}) | ||
.unwrap(); | ||
|
||
assert_scalar( | ||
result, | ||
ScalarValue::Dictionary( | ||
Box::new(DataType::Int8), | ||
Box::new(ScalarValue::Utf8(None)), | ||
), | ||
); | ||
} | ||
|
||
fn assert_scalar(value: ColumnarValue, expected: ScalarValue) { | ||
match value { | ||
ColumnarValue::Array(array) => panic!("expected scalar got {array:?}"), | ||
ColumnarValue::Scalar(scalar) => assert_eq!(scalar, expected), | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The union column used on the sqllogictests contains a single field with type id 3, so this is put to the test
datafusion/datafusion/sqllogictest/src/test_context.rs
Lines 411 to 430 in e4b78c7
datafusion/datafusion/sqllogictest/src/test_context.rs
Lines 117 to 120 in e4b78c7