-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Custom operator support #11137
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
Custom operator support #11137
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
c195050
very rough implementation of custom operators
samuelcolvin 0e25ccf
implement register_parse_custom_operator
samuelcolvin f031f66
cleanup
samuelcolvin 2fb7f7b
more cleanup
samuelcolvin 99d7ae0
fix tests
samuelcolvin 620a32f
move register_parse_custom_operator to FunctionRegistry, fix from_proto
samuelcolvin 18290e6
woops, forgot license
samuelcolvin 5f21379
fix todo on SessionContext
samuelcolvin f4bdfa0
add tests
samuelcolvin e17b827
clean up tests
samuelcolvin 71b7956
snoooooze, fmt
samuelcolvin 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
samuelcolvin marked this conversation as resolved.
Show resolved
Hide resolved
|
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
169 changes: 169 additions & 0 deletions
169
datafusion/core/tests/user_defined/user_defined_custom_operators.rs
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 |
---|---|---|
@@ -0,0 +1,169 @@ | ||
// 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::RecordBatch; | ||
use std::sync::Arc; | ||
|
||
use datafusion::arrow::datatypes::DataType; | ||
use datafusion::common::config::ConfigOptions; | ||
use datafusion::common::tree_node::Transformed; | ||
use datafusion::common::{assert_batches_eq, DFSchema}; | ||
use datafusion::error::Result; | ||
use datafusion::execution::FunctionRegistry; | ||
use datafusion::logical_expr::expr_rewriter::FunctionRewrite; | ||
use datafusion::logical_expr::{ | ||
CustomOperator, Operator, ParseCustomOperator, WrapCustomOperator, | ||
}; | ||
use datafusion::prelude::*; | ||
use datafusion::sql::sqlparser::ast::BinaryOperator; | ||
|
||
#[derive(Debug)] | ||
enum MyCustomOperator { | ||
Arrow, | ||
LongArrow, | ||
} | ||
|
||
impl std::fmt::Display for MyCustomOperator { | ||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
match self { | ||
MyCustomOperator::Arrow => write!(f, "->"), | ||
MyCustomOperator::LongArrow => write!(f, "->>"), | ||
} | ||
} | ||
} | ||
|
||
impl CustomOperator for MyCustomOperator { | ||
fn binary_signature( | ||
&self, | ||
lhs: &DataType, | ||
rhs: &DataType, | ||
) -> Result<(DataType, DataType, DataType)> { | ||
Ok((lhs.clone(), rhs.clone(), lhs.clone())) | ||
} | ||
|
||
fn op_to_sql(&self) -> Result<BinaryOperator> { | ||
match self { | ||
MyCustomOperator::Arrow => Ok(BinaryOperator::Arrow), | ||
MyCustomOperator::LongArrow => Ok(BinaryOperator::LongArrow), | ||
} | ||
} | ||
|
||
fn name(&self) -> &'static str { | ||
match self { | ||
MyCustomOperator::Arrow => "Arrow", | ||
MyCustomOperator::LongArrow => "LongArrow", | ||
} | ||
} | ||
} | ||
|
||
impl TryFrom<&str> for MyCustomOperator { | ||
type Error = (); | ||
|
||
fn try_from(value: &str) -> std::result::Result<Self, Self::Error> { | ||
match value { | ||
"Arrow" => Ok(MyCustomOperator::Arrow), | ||
"LongArrow" => Ok(MyCustomOperator::LongArrow), | ||
_ => Err(()), | ||
} | ||
} | ||
} | ||
|
||
#[derive(Debug)] | ||
struct CustomOperatorParser; | ||
|
||
impl ParseCustomOperator for CustomOperatorParser { | ||
fn name(&self) -> &str { | ||
"CustomOperatorParser" | ||
} | ||
|
||
fn op_from_ast(&self, op: &BinaryOperator) -> Result<Option<Operator>> { | ||
match op { | ||
BinaryOperator::Arrow => Ok(Some(MyCustomOperator::Arrow.into())), | ||
BinaryOperator::LongArrow => Ok(Some(MyCustomOperator::LongArrow.into())), | ||
_ => Ok(None), | ||
} | ||
} | ||
|
||
fn op_from_name(&self, raw_op: &str) -> Result<Option<Operator>> { | ||
if let Ok(op) = MyCustomOperator::try_from(raw_op) { | ||
Ok(Some(op.into())) | ||
} else { | ||
Ok(None) | ||
} | ||
} | ||
} | ||
|
||
impl FunctionRewrite for CustomOperatorParser { | ||
fn name(&self) -> &str { | ||
"CustomOperatorParser" | ||
} | ||
|
||
fn rewrite( | ||
&self, | ||
expr: Expr, | ||
_schema: &DFSchema, | ||
_config: &ConfigOptions, | ||
) -> Result<Transformed<Expr>> { | ||
if let Expr::BinaryExpr(bin_expr) = &expr { | ||
if let Operator::Custom(WrapCustomOperator(op)) = &bin_expr.op { | ||
if let Ok(pg_op) = MyCustomOperator::try_from(op.name()) { | ||
// return BinaryExpr with a different operator | ||
let mut bin_expr = bin_expr.clone(); | ||
bin_expr.op = match pg_op { | ||
MyCustomOperator::Arrow => Operator::StringConcat, | ||
MyCustomOperator::LongArrow => Operator::Plus, | ||
}; | ||
return Ok(Transformed::yes(Expr::BinaryExpr(bin_expr))); | ||
} | ||
} | ||
} | ||
Ok(Transformed::no(expr)) | ||
} | ||
} | ||
|
||
async fn plan_and_collect(sql: &str) -> Result<Vec<RecordBatch>> { | ||
let mut ctx = SessionContext::new(); | ||
ctx.register_function_rewrite(Arc::new(CustomOperatorParser))?; | ||
ctx.register_parse_custom_operator(Arc::new(CustomOperatorParser))?; | ||
ctx.sql(sql).await?.collect().await | ||
} | ||
|
||
#[tokio::test] | ||
async fn test_custom_operators_arrow() { | ||
let actual = plan_and_collect("select 'foo'->'bar';").await.unwrap(); | ||
let expected = [ | ||
"+----------------------------+", | ||
"| Utf8(\"foo\") -> Utf8(\"bar\") |", | ||
"+----------------------------+", | ||
"| foobar |", | ||
"+----------------------------+", | ||
]; | ||
assert_batches_eq!(&expected, &actual); | ||
} | ||
|
||
#[tokio::test] | ||
async fn test_custom_operators_long_arrow() { | ||
let actual = plan_and_collect("select 1->>2;").await.unwrap(); | ||
let expected = [ | ||
"+-----------------------+", | ||
"| Int64(1) ->> Int64(2) |", | ||
"+-----------------------+", | ||
"| 3 |", | ||
"+-----------------------+", | ||
]; | ||
assert_batches_eq!(&expected, &actual); | ||
} |
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.