-
Couldn't load subscription status.
- Fork 1.7k
Support ORDER BY in AggregateUDF #9249
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
Closed
Closed
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
b94f70f
first draft
jayzhan211 c743d13
clippy fix
jayzhan211 3a7e965
cleanup
jayzhan211 4917f56
use one vector for ordering req
jayzhan211 c9e8641
add sort exprs to accumulator
jayzhan211 3a5f0d1
clippy
jayzhan211 a3ea00a
cleanup
jayzhan211 f349f21
fix doc test
jayzhan211 6fcdaac
change to ref
jayzhan211 c3512a6
fix typo
jayzhan211 092d46e
fix doc
jayzhan211 8592e6b
fmt
jayzhan211 0f8fc24
move schema and logical ordering exprs
jayzhan211 3185f9f
remove redudant info
jayzhan211 3ecc772
rename
jayzhan211 faadc63
cleanup
jayzhan211 7e33910
add ignore nulls
jayzhan211 cfffcbf
Merge remote-tracking branch 'upstream/main' into udf-order-2
jayzhan211 6aaa15c
fix conflict
jayzhan211 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -20,7 +20,7 @@ | |
|
|
||
| use arrow::{array::AsArray, datatypes::Fields}; | ||
| use arrow_array::{types::UInt64Type, Int32Array, PrimitiveArray, StructArray}; | ||
| use arrow_schema::Schema; | ||
| use arrow_schema::{Schema, SortOptions}; | ||
| use std::sync::{ | ||
| atomic::{AtomicBool, Ordering}, | ||
| Arc, | ||
|
|
@@ -45,9 +45,11 @@ use datafusion::{ | |
| }; | ||
| use datafusion_common::{assert_contains, cast::as_primitive_array, exec_err}; | ||
| use datafusion_expr::{ | ||
| create_udaf, AggregateUDFImpl, GroupsAccumulator, SimpleAggregateUDF, | ||
| create_udaf, create_udaf_with_ordering, AggregateUDFImpl, Expr, GroupsAccumulator, | ||
| SimpleAggregateUDF, | ||
| }; | ||
| use datafusion_physical_expr::expressions::AvgAccumulator; | ||
| use datafusion_physical_expr::expressions::{self, FirstValueAccumulator}; | ||
| use datafusion_physical_expr::{expressions::AvgAccumulator, PhysicalSortExpr}; | ||
|
|
||
| /// Test to show the contents of the setup | ||
| #[tokio::test] | ||
|
|
@@ -209,6 +211,102 @@ async fn execute(ctx: &SessionContext, sql: &str) -> Result<Vec<RecordBatch>> { | |
| ctx.sql(sql).await?.collect().await | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn simple_udaf_order() -> Result<()> { | ||
| let schema = Schema::new(vec![ | ||
| Field::new("a", DataType::Int32, false), | ||
| Field::new("b", DataType::Int32, false), | ||
| ]); | ||
|
|
||
| let batch = RecordBatch::try_new( | ||
| Arc::new(schema.clone()), | ||
| vec![ | ||
| Arc::new(Int32Array::from(vec![1, 2, 3, 4])), | ||
| Arc::new(Int32Array::from(vec![1, 1, 2, 2])), | ||
| ], | ||
| )?; | ||
|
|
||
| let ctx = SessionContext::new(); | ||
|
|
||
| let provider = MemTable::try_new(Arc::new(schema.clone()), vec![vec![batch]])?; | ||
| ctx.register_table("t", Arc::new(provider))?; | ||
|
|
||
| fn create_accumulator( | ||
jayzhan211 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| data_type: &DataType, | ||
| order_by: &[Expr], | ||
| schema: &Schema, | ||
| ) -> Result<Box<dyn Accumulator>> { | ||
| let mut all_sort_orders = vec![]; | ||
|
|
||
| // Construct PhysicalSortExpr objects from Expr objects: | ||
| let mut sort_exprs = vec![]; | ||
| for expr in order_by { | ||
| if let Expr::Sort(sort) = expr { | ||
| if let Expr::Column(col) = sort.expr.as_ref() { | ||
| let name = &col.name; | ||
| let e = expressions::col(name, schema)?; | ||
| sort_exprs.push(PhysicalSortExpr { | ||
| expr: e, | ||
| options: SortOptions { | ||
| descending: !sort.asc, | ||
| nulls_first: sort.nulls_first, | ||
| }, | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| if !sort_exprs.is_empty() { | ||
| all_sort_orders.extend(sort_exprs); | ||
| } | ||
|
|
||
| let ordering_req = all_sort_orders; | ||
|
|
||
| let ordering_dtypes = ordering_req | ||
| .iter() | ||
| .map(|e| e.expr.data_type(schema)) | ||
| .collect::<Result<Vec<_>>>()?; | ||
|
|
||
| let acc = FirstValueAccumulator::try_new( | ||
| data_type, | ||
| &ordering_dtypes, | ||
| ordering_req, | ||
| false, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| )?; | ||
| Ok(Box::new(acc)) | ||
| } | ||
|
|
||
| // define a udaf, using a DataFusion's accumulator | ||
| let my_first = create_udaf_with_ordering( | ||
| "my_first", | ||
| vec![DataType::Int32], | ||
| Arc::new(DataType::Int32), | ||
| Volatility::Immutable, | ||
| Arc::new(create_accumulator), | ||
| Arc::new(vec![DataType::Int32, DataType::Int32, DataType::Boolean]), | ||
| ); | ||
|
|
||
| ctx.register_udaf(my_first); | ||
|
|
||
| // Should be the same as `SELECT FIRST_VALUE(a order by a) FROM t group by b order by b` | ||
| let result = ctx | ||
| .sql("SELECT MY_FIRST(a order by a desc) FROM t group by b order by b") | ||
| .await? | ||
| .collect() | ||
| .await?; | ||
|
|
||
| let expected = [ | ||
| "+---------------+", | ||
| "| my_first(t.a) |", | ||
| "+---------------+", | ||
| "| 2 |", | ||
| "| 4 |", | ||
| "+---------------+", | ||
| ]; | ||
| assert_batches_eq!(expected, &result); | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| /// tests the creation, registration and usage of a UDAF | ||
| #[tokio::test] | ||
| async fn simple_udaf() -> Result<()> { | ||
|
|
@@ -234,7 +332,7 @@ async fn simple_udaf() -> Result<()> { | |
| vec![DataType::Float64], | ||
| Arc::new(DataType::Float64), | ||
| Volatility::Immutable, | ||
| Arc::new(|_| Ok(Box::<AvgAccumulator>::default())), | ||
| Arc::new(|_, _, _| Ok(Box::<AvgAccumulator>::default())), | ||
| Arc::new(vec![DataType::UInt64, DataType::Float64]), | ||
| ); | ||
|
|
||
|
|
@@ -262,7 +360,7 @@ async fn deregister_udaf() -> Result<()> { | |
| vec![DataType::Float64], | ||
| Arc::new(DataType::Float64), | ||
| Volatility::Immutable, | ||
| Arc::new(|_| Ok(Box::<AvgAccumulator>::default())), | ||
| Arc::new(|_, _, _| Ok(Box::<AvgAccumulator>::default())), | ||
| Arc::new(vec![DataType::UInt64, DataType::Float64]), | ||
| ); | ||
|
|
||
|
|
@@ -290,7 +388,7 @@ async fn case_sensitive_identifiers_user_defined_aggregates() -> Result<()> { | |
| vec![DataType::Float64], | ||
| Arc::new(DataType::Float64), | ||
| Volatility::Immutable, | ||
| Arc::new(|_| Ok(Box::<AvgAccumulator>::default())), | ||
| Arc::new(|_, _, _| Ok(Box::<AvgAccumulator>::default())), | ||
| Arc::new(vec![DataType::UInt64, DataType::Float64]), | ||
| ); | ||
|
|
||
|
|
@@ -333,7 +431,7 @@ async fn test_user_defined_functions_with_alias() -> Result<()> { | |
| vec![DataType::Float64], | ||
| Arc::new(DataType::Float64), | ||
| Volatility::Immutable, | ||
| Arc::new(|_| Ok(Box::<AvgAccumulator>::default())), | ||
| Arc::new(|_, _, _| Ok(Box::<AvgAccumulator>::default())), | ||
| Arc::new(vec![DataType::UInt64, DataType::Float64]), | ||
| ) | ||
| .with_aliases(vec!["dummy_alias"]); | ||
|
|
@@ -497,7 +595,7 @@ impl TimeSum { | |
|
|
||
| let captured_state = Arc::clone(&test_state); | ||
| let accumulator: AccumulatorFactoryFunction = | ||
| Arc::new(move |_| Ok(Box::new(Self::new(Arc::clone(&captured_state))))); | ||
| Arc::new(move |_, _, _| Ok(Box::new(Self::new(Arc::clone(&captured_state))))); | ||
|
|
||
| let time_sum = AggregateUDF::from(SimpleAggregateUDF::new( | ||
| name, | ||
|
|
@@ -596,7 +694,7 @@ impl FirstSelector { | |
| let signatures = vec![TypeSignature::Exact(Self::input_datatypes())]; | ||
|
|
||
| let accumulator: AccumulatorFactoryFunction = | ||
| Arc::new(|_| Ok(Box::new(Self::new()))); | ||
| Arc::new(|_, _, _| Ok(Box::new(Self::new()))); | ||
|
|
||
| let volatility = Volatility::Immutable; | ||
|
|
||
|
|
@@ -717,7 +815,12 @@ impl AggregateUDFImpl for TestGroupsAccumulator { | |
| Ok(DataType::UInt64) | ||
| } | ||
|
|
||
| fn accumulator(&self, _arg: &DataType) -> Result<Box<dyn Accumulator>> { | ||
| fn accumulator( | ||
| &self, | ||
| _arg: &DataType, | ||
| _sort_exprs: &[Expr], | ||
| _schema: &Schema, | ||
| ) -> Result<Box<dyn Accumulator>> { | ||
| // should use groups accumulator | ||
| panic!("accumulator shouldn't invoke"); | ||
| } | ||
|
|
||
This file contains hidden or 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.
Uh oh!
There was an error while loading. Please reload this page.