You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "jcsherin (via GitHub)" <gi...@apache.org> on 2024/10/10 17:47:51 UTC
[PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
jcsherin opened a new pull request, #12857:
URL: https://github.com/apache/datafusion/pull/12857
## Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
-->
Closes #12802.
## Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
## What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
## Are these changes tested?
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
-->
## Are there any user-facing changes?
<!--
If there are user-facing changes then we may require documentation to be updated before approving the PR.
-->
<!--
If there are any breaking changes to public APIs, please add the `api change` label.
-->
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb merged PR #12857:
URL: https://github.com/apache/datafusion/pull/12857
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2417731313
That works. Will keep this PR as draft until the bug fix is complete. Thanks ๐
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2417686251
@alamb
> CI tests are still failing it seems
The bug fix relies on rewriting the NULL expression passed as argument to `lead` or `lag` to match the data type of the default value.
Right now this feature is missing in `WindowUDF`. To be specific, the `expressions` method in `BuiltInWindowFunctionExpr`:
https://github.com/apache/datafusion/blob/16589b56a161a8ff13d16b3e55d7abbfb9d94f4b/datafusion/physical-expr/src/window/nth_value.rs#L115-L117
I think we need to add a similar API in `WindowUDF` to complete this bugfix.
For now I have disabled the new sqllogictests and marked them as TODO in [270a203](https://github.com/apache/datafusion/pull/12857/commits/270a2030637012d549c001e973a0a1bb6b3d4dd0).
I'll do a follow on PR to add this feature and squash the bug (again). Hope that is alright?
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2417703761
> I'll do a follow on PR to add this feature and squash the bug (again). Hope that is alright?
Yes, thank you
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797694362
##########
datafusion/proto/proto/datafusion.proto:
##########
@@ -526,7 +526,7 @@ message WindowExprNode {
string udaf = 3;
string udwf = 9;
}
- LogicalExprNode expr = 4;
+ repeated LogicalExprNode exprs = 4;
Review Comment:
**<ins>This change is not backwards compatible!</ins>**
This is necessary to correctly serialize expression functions like `lag(col("a"), Some(2), Some(100))` which has more than 1 argument.
Without this gets serialized into `lag(col("a"))` ignoring the second, and third arguments and results in an error when deserialized.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797693389
##########
datafusion/functions-window/src/utils.rs:
##########
Review Comment:
These functions are copied from `datafusion/physical-plan/src/windows/mod.rs`. It cannot be reused in `physical-plan` because of cyclic dependency.
- after #12694 is converted `get_scalar_value_from_args` can be removed from `physical-plan`.
- after #12649 is converted `get_signed_integer` can be removed from `physical-plan`.
The `get_casted_value` function is already removed from `physical-plan` in this PR.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797735056
##########
datafusion/proto/src/logical_plan/to_proto.rs:
##########
@@ -333,25 +331,19 @@ pub fn serialize_expr(
)
}
};
- let arg_expr: Option<Box<protobuf::LogicalExprNode>> = if !args.is_empty() {
- let arg = &args[0];
- Some(Box::new(serialize_expr(arg, codec)?))
- } else {
- None
- };
let partition_by = serialize_exprs(partition_by, codec)?;
let order_by = serialize_sorts(order_by, codec)?;
let window_frame: Option<protobuf::WindowFrame> =
Some(window_frame.try_into()?);
- let window_expr = Box::new(protobuf::WindowExprNode {
- expr: arg_expr,
+ let window_expr = protobuf::WindowExprNode {
+ exprs: serialize_exprs(args, codec)?,
Review Comment:
Serialize all arguments of window function.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1805409602
##########
datafusion/functions-window-common/src/expr.rs:
##########
@@ -0,0 +1,64 @@
+// 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 datafusion_common::arrow::datatypes::DataType;
+use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
+use std::sync::Arc;
+
+/// Arguments passed to user-defined window function
Review Comment:
๐
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797694362
##########
datafusion/proto/proto/datafusion.proto:
##########
@@ -526,7 +526,7 @@ message WindowExprNode {
string udaf = 3;
string udwf = 9;
}
- LogicalExprNode expr = 4;
+ repeated LogicalExprNode exprs = 4;
Review Comment:
**<ins>This change is not backwards compatible!</ins>**
- Adds `repeated` keyword to convert to `Vec<LogicalExprNode>`
- Renames from `expr` to `exprs`
This is necessary to correctly serialize expression functions like `lag(col("a"), Some(2), Some(100))` which has more than 1 argument.
Otherwise it gets serialized into `lag(col("a"))` ignoring the second, and third arguments and results in a `SchemaError::FieldNotFound` error when deserialized.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2417608076
CI tests are still failing it seems
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797694362
##########
datafusion/proto/proto/datafusion.proto:
##########
@@ -526,7 +526,7 @@ message WindowExprNode {
string udaf = 3;
string udwf = 9;
}
- LogicalExprNode expr = 4;
+ repeated LogicalExprNode exprs = 4;
Review Comment:
**<ins>This change is not backwards compatible!</ins>**
This is necessary to correctly serialize expression functions like `lag(col("a"), Some(2), Some(100))` which has more than 1 argument.
Otherwise it gets serialized into `lag(col("a"))` ignoring the second, and third arguments and results in a `SchemaError::FieldNotFound` error when deserialized.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797694362
##########
datafusion/proto/proto/datafusion.proto:
##########
@@ -526,7 +526,7 @@ message WindowExprNode {
string udaf = 3;
string udwf = 9;
}
- LogicalExprNode expr = 4;
+ repeated LogicalExprNode exprs = 4;
Review Comment:
**<ins>This change is not backwards compatible!</ins>**
- Adds `repeated` keyword to convert to `Vec<LogicalExprNode>`
- Renames from `expr` to `exprs`
This is necessary to correctly serialize expression functions like `lag(col("a"), Some(2), Some(100))` which has more than 1 argument.
Otherwise it gets serialized into `lag(col("a"))` ignoring the second, and third arguments and results in a `SchemaError::FieldNotFound` error when deserialized.
This applies to all window expressions - built-in, aggregate and udwf.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797116039
##########
datafusion/functions-window/src/lead_lag.rs:
##########
@@ -15,125 +15,200 @@
// specific language governing permissions and limitations
// under the License.
-//! Defines physical expression for `lead` and `lag` that can evaluated
-//! at runtime during query execution
-use crate::window::BuiltInWindowFunctionExpr;
-use crate::PhysicalExpr;
-use arrow::array::ArrayRef;
-use arrow::datatypes::{DataType, Field};
-use arrow_array::Array;
+//! `lead` and `lag` window function implementations
+
+use crate::utils::{get_casted_value, get_scalar_value_from_args, get_signed_integer};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{arrow_datafusion_err, DataFusionError, Result, ScalarValue};
-use datafusion_expr::PartitionEvaluator;
+use datafusion_expr::{
+ Literal, PartitionEvaluator, ReversedUDWF, Signature, TypeSignature, Volatility,
+ WindowUDFImpl,
+};
+use datafusion_functions_window_common::field::WindowUDFFieldArgs;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
use std::any::Any;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::{Neg, Range};
use std::sync::Arc;
-/// window shift expression
+get_or_init_udwf!(
+ Lag,
+ lag,
+ "Returns the row value that precedes the current row by a specified \
+ offset within partition. If no such row exists, then returns the \
+ default value.",
+ WindowShift::lag
+);
+get_or_init_udwf!(
+ Lead,
+ lead,
+ "Returns the value from a row that follows the current row by a \
+ specified offset within the partition. If no such row exists, then \
+ returns the default value.",
+ WindowShift::lead
+);
+
+/// Create an expression to represent the `lag` window function
+///
+/// returns value evaluated at the row that is offset rows before the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lag(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lag_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
+/// Create an expression to represent the `lead` window function
+///
+/// returns value evaluated at the row that is offset rows after the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lead(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lead_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
#[derive(Debug)]
-pub struct WindowShift {
- name: String,
- /// Output data type
- data_type: DataType,
- shift_offset: i64,
- expr: Arc<dyn PhysicalExpr>,
- default_value: ScalarValue,
- ignore_nulls: bool,
+enum WindowShiftKind {
+ Lag,
+ Lead,
}
-impl WindowShift {
- /// Get shift_offset of window shift expression
- pub fn get_shift_offset(&self) -> i64 {
- self.shift_offset
+impl WindowShiftKind {
+ fn name(&self) -> &'static str {
+ match self {
+ WindowShiftKind::Lag => "lag",
+ WindowShiftKind::Lead => "lead",
+ }
}
- /// Get the default_value for window shift expression.
- pub fn get_default_value(&self) -> ScalarValue {
- self.default_value.clone()
+ /// In [`WindowShiftEvaluator`] a positive offset is used to signal
+ /// computation of `lag()`. So here we negate the input offset
+ /// value for computing `lead()`.
+ fn shift_offset(&self, value: Option<i64>) -> i64 {
+ match self {
+ WindowShiftKind::Lag => value.unwrap_or(1),
+ WindowShiftKind::Lead => value.map(|v| v.neg()).unwrap_or(-1),
+ }
}
}
-/// lead() window function
-pub fn lead(
- name: String,
- data_type: DataType,
- expr: Arc<dyn PhysicalExpr>,
- shift_offset: Option<i64>,
- default_value: ScalarValue,
- ignore_nulls: bool,
-) -> WindowShift {
- WindowShift {
- name,
- data_type,
- shift_offset: shift_offset.map(|v| v.neg()).unwrap_or(-1),
- expr,
- default_value,
- ignore_nulls,
- }
+/// window shift expression
+#[derive(Debug)]
+pub struct WindowShift {
+ signature: Signature,
+ kind: WindowShiftKind,
}
-/// lag() window function
-pub fn lag(
- name: String,
- data_type: DataType,
- expr: Arc<dyn PhysicalExpr>,
- shift_offset: Option<i64>,
- default_value: ScalarValue,
- ignore_nulls: bool,
-) -> WindowShift {
- WindowShift {
- name,
- data_type,
- shift_offset: shift_offset.unwrap_or(1),
- expr,
- default_value,
- ignore_nulls,
+impl WindowShift {
+ fn new(kind: WindowShiftKind) -> Self {
+ Self {
+ signature: Signature::one_of(
+ vec![
+ TypeSignature::Any(1),
+ TypeSignature::Any(2),
+ TypeSignature::Any(3),
+ ],
+ Volatility::Immutable,
+ ),
+ kind,
+ }
+ }
+
+ pub fn lag() -> Self {
+ Self::new(WindowShiftKind::Lag)
+ }
+
+ pub fn lead() -> Self {
+ Self::new(WindowShiftKind::Lead)
}
}
-impl BuiltInWindowFunctionExpr for WindowShift {
- /// Return a reference to Any that can be used for downcasting
+impl WindowUDFImpl for WindowShift {
fn as_any(&self) -> &dyn Any {
self
}
- fn field(&self) -> Result<Field> {
- let nullable = true;
- Ok(Field::new(&self.name, self.data_type.clone(), nullable))
+ fn name(&self) -> &str {
+ self.kind.name()
}
- fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
- vec![Arc::clone(&self.expr)]
+ fn signature(&self) -> &Signature {
+ &self.signature
}
- fn name(&self) -> &str {
- &self.name
- }
+ fn partition_evaluator(
+ &self,
+ partition_evaluator_args: PartitionEvaluatorArgs,
+ ) -> Result<Box<dyn PartitionEvaluator>> {
+ let shift_offset =
+ get_scalar_value_from_args(partition_evaluator_args.input_exprs(), 1)?
+ .map(get_signed_integer)
+ .map_or(Ok(None), |v| v.map(Some))
+ .map(|n| self.kind.shift_offset(n))
+ .map(|offset| {
+ if partition_evaluator_args.is_reversed() {
+ -offset
+ } else {
+ offset
+ }
+ })?;
+ let return_type = partition_evaluator_args
+ .input_types()
+ .first()
+ .unwrap_or(&DataType::Null);
+ let default_value = get_casted_value(
+ get_scalar_value_from_args(partition_evaluator_args.input_exprs(), 2)?,
+ return_type,
+ )?;
Review Comment:
https://github.com/apache/datafusion/blob/a8d3fae21d12a9caafad77a11b8a22bcfe9555fd/datafusion/physical-plan/src/windows/mod.rs#L254-L285
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797110630
##########
datafusion/functions-window/src/lead_lag.rs:
##########
@@ -15,125 +15,200 @@
// specific language governing permissions and limitations
// under the License.
-//! Defines physical expression for `lead` and `lag` that can evaluated
-//! at runtime during query execution
-use crate::window::BuiltInWindowFunctionExpr;
-use crate::PhysicalExpr;
-use arrow::array::ArrayRef;
-use arrow::datatypes::{DataType, Field};
-use arrow_array::Array;
+//! `lead` and `lag` window function implementations
+
+use crate::utils::{get_casted_value, get_scalar_value_from_args, get_signed_integer};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{arrow_datafusion_err, DataFusionError, Result, ScalarValue};
-use datafusion_expr::PartitionEvaluator;
+use datafusion_expr::{
+ Literal, PartitionEvaluator, ReversedUDWF, Signature, TypeSignature, Volatility,
+ WindowUDFImpl,
+};
+use datafusion_functions_window_common::field::WindowUDFFieldArgs;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
use std::any::Any;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::{Neg, Range};
use std::sync::Arc;
-/// window shift expression
+get_or_init_udwf!(
+ Lag,
+ lag,
+ "Returns the row value that precedes the current row by a specified \
+ offset within partition. If no such row exists, then returns the \
+ default value.",
+ WindowShift::lag
+);
+get_or_init_udwf!(
+ Lead,
+ lead,
+ "Returns the value from a row that follows the current row by a \
+ specified offset within the partition. If no such row exists, then \
+ returns the default value.",
+ WindowShift::lead
+);
+
+/// Create an expression to represent the `lag` window function
+///
+/// returns value evaluated at the row that is offset rows before the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lag(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lag_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
+/// Create an expression to represent the `lead` window function
+///
+/// returns value evaluated at the row that is offset rows after the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
Review Comment:
Copied verbatim from built-in window function
https://github.com/apache/datafusion/blob/a8d3fae21d12a9caafad77a11b8a22bcfe9555fd/datafusion/expr/src/built_in_window_function.rs#L52-L56
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2417308572
Marking as draft so we don't accidentally merge it before the fixes are complete
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1803620683
##########
datafusion/functions-window/src/lead_lag.rs:
##########
@@ -15,125 +15,208 @@
// specific language governing permissions and limitations
// under the License.
-//! Defines physical expression for `lead` and `lag` that can evaluated
-//! at runtime during query execution
-use crate::window::BuiltInWindowFunctionExpr;
-use crate::PhysicalExpr;
-use arrow::array::ArrayRef;
-use arrow::datatypes::{DataType, Field};
-use arrow_array::Array;
+//! `lead` and `lag` window function implementations
+
+use crate::utils::{
+ get_casted_value, get_scalar_value_from_args, get_signed_integer,
+ rewrite_null_expr_and_data_type,
+};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{arrow_datafusion_err, DataFusionError, Result, ScalarValue};
-use datafusion_expr::PartitionEvaluator;
+use datafusion_expr::{
+ Literal, PartitionEvaluator, ReversedUDWF, Signature, TypeSignature, Volatility,
+ WindowUDFImpl,
+};
+use datafusion_functions_window_common::field::WindowUDFFieldArgs;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
use std::any::Any;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::{Neg, Range};
use std::sync::Arc;
-/// window shift expression
+get_or_init_udwf!(
+ Lag,
+ lag,
+ "Returns the row value that precedes the current row by a specified \
+ offset within partition. If no such row exists, then returns the \
+ default value.",
+ WindowShift::lag
+);
+get_or_init_udwf!(
+ Lead,
+ lead,
+ "Returns the value from a row that follows the current row by a \
+ specified offset within the partition. If no such row exists, then \
+ returns the default value.",
+ WindowShift::lead
+);
+
+/// Create an expression to represent the `lag` window function
+///
+/// returns value evaluated at the row that is offset rows before the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lag(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lag_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
+/// Create an expression to represent the `lead` window function
+///
+/// returns value evaluated at the row that is offset rows after the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lead(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lead_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
#[derive(Debug)]
-pub struct WindowShift {
- name: String,
- /// Output data type
- data_type: DataType,
- shift_offset: i64,
- expr: Arc<dyn PhysicalExpr>,
- default_value: ScalarValue,
- ignore_nulls: bool,
+enum WindowShiftKind {
+ Lag,
+ Lead,
}
-impl WindowShift {
- /// Get shift_offset of window shift expression
- pub fn get_shift_offset(&self) -> i64 {
- self.shift_offset
+impl WindowShiftKind {
+ fn name(&self) -> &'static str {
+ match self {
+ WindowShiftKind::Lag => "lag",
+ WindowShiftKind::Lead => "lead",
+ }
}
- /// Get the default_value for window shift expression.
- pub fn get_default_value(&self) -> ScalarValue {
- self.default_value.clone()
+ /// In [`WindowShiftEvaluator`] a positive offset is used to signal
+ /// computation of `lag()`. So here we negate the input offset
+ /// value when computing `lead()`.
+ fn shift_offset(&self, value: Option<i64>) -> i64 {
+ match self {
+ WindowShiftKind::Lag => value.unwrap_or(1),
+ WindowShiftKind::Lead => value.map(|v| v.neg()).unwrap_or(-1),
+ }
}
}
-/// lead() window function
-pub fn lead(
- name: String,
- data_type: DataType,
- expr: Arc<dyn PhysicalExpr>,
- shift_offset: Option<i64>,
- default_value: ScalarValue,
- ignore_nulls: bool,
-) -> WindowShift {
- WindowShift {
- name,
- data_type,
- shift_offset: shift_offset.map(|v| v.neg()).unwrap_or(-1),
- expr,
- default_value,
- ignore_nulls,
- }
+/// window shift expression
+#[derive(Debug)]
+pub struct WindowShift {
+ signature: Signature,
+ kind: WindowShiftKind,
}
-/// lag() window function
-pub fn lag(
- name: String,
- data_type: DataType,
- expr: Arc<dyn PhysicalExpr>,
- shift_offset: Option<i64>,
- default_value: ScalarValue,
- ignore_nulls: bool,
-) -> WindowShift {
- WindowShift {
- name,
- data_type,
- shift_offset: shift_offset.unwrap_or(1),
- expr,
- default_value,
- ignore_nulls,
+impl WindowShift {
+ fn new(kind: WindowShiftKind) -> Self {
+ Self {
+ signature: Signature::one_of(
+ vec![
+ TypeSignature::Any(1),
+ TypeSignature::Any(2),
+ TypeSignature::Any(3),
+ ],
+ Volatility::Immutable,
+ ),
+ kind,
+ }
+ }
+
+ pub fn lag() -> Self {
+ Self::new(WindowShiftKind::Lag)
+ }
+
+ pub fn lead() -> Self {
+ Self::new(WindowShiftKind::Lead)
}
}
-impl BuiltInWindowFunctionExpr for WindowShift {
- /// Return a reference to Any that can be used for downcasting
+impl WindowUDFImpl for WindowShift {
fn as_any(&self) -> &dyn Any {
self
}
- fn field(&self) -> Result<Field> {
- let nullable = true;
- Ok(Field::new(&self.name, self.data_type.clone(), nullable))
+ fn name(&self) -> &str {
+ self.kind.name()
}
- fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
- vec![Arc::clone(&self.expr)]
+ fn signature(&self) -> &Signature {
+ &self.signature
}
- fn name(&self) -> &str {
- &self.name
- }
+ fn partition_evaluator(
+ &self,
+ partition_evaluator_args: PartitionEvaluatorArgs,
+ ) -> Result<Box<dyn PartitionEvaluator>> {
+ let shift_offset =
+ get_scalar_value_from_args(partition_evaluator_args.input_exprs(), 1)?
+ .map(get_signed_integer)
+ .map_or(Ok(None), |v| v.map(Some))
+ .map(|n| self.kind.shift_offset(n))
+ .map(|offset| {
+ if partition_evaluator_args.is_reversed() {
+ -offset
+ } else {
+ offset
+ }
+ })?;
+ let return_type = partition_evaluator_args
+ .input_types()
+ .first()
+ .unwrap_or(&DataType::Null);
+ // See https://github.com/apache/datafusion/pull/12811
+ let (_expr, return_type) = rewrite_null_expr_and_data_type(
+ partition_evaluator_args.input_exprs(),
+ return_type,
+ )?;
Review Comment:
- Ported from https://github.com/apache/datafusion/pull/12811
The above bug fix in `BuiltInWindowFunction:{Lead, Lag}` rewrites the `NULL` expression to match the type of default value (if provided).
Right now this feature for overwriting arguments to user-defined window function is missing in `WindowUDF`. So for the moment this fix cannot be applied and the newly added regression sqllogictests will fail.
I'll have to look into bridging the gap between `WindowUDF` and `BuiltInWindowFunction` in this case.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1801352754
##########
datafusion/proto/tests/cases/roundtrip_logical_plan.rs:
##########
@@ -944,6 +944,12 @@ async fn roundtrip_expr_api() -> Result<()> {
rank(),
dense_rank(),
percent_rank(),
+ lead(col("b"), None, None),
Review Comment:
๐ป
##########
datafusion/proto/proto/datafusion.proto:
##########
@@ -526,7 +526,7 @@ message WindowExprNode {
string udaf = 3;
string udwf = 9;
}
- LogicalExprNode expr = 4;
+ repeated LogicalExprNode exprs = 4;
Review Comment:
I think it is fine as the protobuf isn't guaranteed to be compatible across versions, see https://docs.rs/datafusion-proto/latest/datafusion_proto/#version-compatibility
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797110630
##########
datafusion/functions-window/src/lead_lag.rs:
##########
@@ -15,125 +15,200 @@
// specific language governing permissions and limitations
// under the License.
-//! Defines physical expression for `lead` and `lag` that can evaluated
-//! at runtime during query execution
-use crate::window::BuiltInWindowFunctionExpr;
-use crate::PhysicalExpr;
-use arrow::array::ArrayRef;
-use arrow::datatypes::{DataType, Field};
-use arrow_array::Array;
+//! `lead` and `lag` window function implementations
+
+use crate::utils::{get_casted_value, get_scalar_value_from_args, get_signed_integer};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{arrow_datafusion_err, DataFusionError, Result, ScalarValue};
-use datafusion_expr::PartitionEvaluator;
+use datafusion_expr::{
+ Literal, PartitionEvaluator, ReversedUDWF, Signature, TypeSignature, Volatility,
+ WindowUDFImpl,
+};
+use datafusion_functions_window_common::field::WindowUDFFieldArgs;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
use std::any::Any;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::{Neg, Range};
use std::sync::Arc;
-/// window shift expression
+get_or_init_udwf!(
+ Lag,
+ lag,
+ "Returns the row value that precedes the current row by a specified \
+ offset within partition. If no such row exists, then returns the \
+ default value.",
+ WindowShift::lag
+);
+get_or_init_udwf!(
+ Lead,
+ lead,
+ "Returns the value from a row that follows the current row by a \
+ specified offset within the partition. If no such row exists, then \
+ returns the default value.",
+ WindowShift::lead
+);
+
+/// Create an expression to represent the `lag` window function
+///
+/// returns value evaluated at the row that is offset rows before the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lag(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lag_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
+/// Create an expression to represent the `lead` window function
+///
+/// returns value evaluated at the row that is offset rows after the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
Review Comment:
Same as https://github.com/apache/datafusion/blob/a8d3fae21d12a9caafad77a11b8a22bcfe9555fd/datafusion/expr/src/built_in_window_function.rs#L52-L56
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797109660
##########
datafusion/functions-window/src/lead_lag.rs:
##########
@@ -15,125 +15,200 @@
// specific language governing permissions and limitations
// under the License.
-//! Defines physical expression for `lead` and `lag` that can evaluated
-//! at runtime during query execution
-use crate::window::BuiltInWindowFunctionExpr;
-use crate::PhysicalExpr;
-use arrow::array::ArrayRef;
-use arrow::datatypes::{DataType, Field};
-use arrow_array::Array;
+//! `lead` and `lag` window function implementations
+
+use crate::utils::{get_casted_value, get_scalar_value_from_args, get_signed_integer};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{arrow_datafusion_err, DataFusionError, Result, ScalarValue};
-use datafusion_expr::PartitionEvaluator;
+use datafusion_expr::{
+ Literal, PartitionEvaluator, ReversedUDWF, Signature, TypeSignature, Volatility,
+ WindowUDFImpl,
+};
+use datafusion_functions_window_common::field::WindowUDFFieldArgs;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
use std::any::Any;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::{Neg, Range};
use std::sync::Arc;
-/// window shift expression
+get_or_init_udwf!(
+ Lag,
+ lag,
+ "Returns the row value that precedes the current row by a specified \
+ offset within partition. If no such row exists, then returns the \
+ default value.",
+ WindowShift::lag
+);
+get_or_init_udwf!(
+ Lead,
+ lead,
+ "Returns the value from a row that follows the current row by a \
+ specified offset within the partition. If no such row exists, then \
+ returns the default value.",
+ WindowShift::lead
+);
+
+/// Create an expression to represent the `lag` window function
+///
+/// returns value evaluated at the row that is offset rows before the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
Review Comment:
Same as https://github.com/apache/datafusion/blob/a8d3fae21d12a9caafad77a11b8a22bcfe9555fd/datafusion/expr/src/built_in_window_function.rs#L47-L51
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797109660
##########
datafusion/functions-window/src/lead_lag.rs:
##########
@@ -15,125 +15,200 @@
// specific language governing permissions and limitations
// under the License.
-//! Defines physical expression for `lead` and `lag` that can evaluated
-//! at runtime during query execution
-use crate::window::BuiltInWindowFunctionExpr;
-use crate::PhysicalExpr;
-use arrow::array::ArrayRef;
-use arrow::datatypes::{DataType, Field};
-use arrow_array::Array;
+//! `lead` and `lag` window function implementations
+
+use crate::utils::{get_casted_value, get_scalar_value_from_args, get_signed_integer};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{arrow_datafusion_err, DataFusionError, Result, ScalarValue};
-use datafusion_expr::PartitionEvaluator;
+use datafusion_expr::{
+ Literal, PartitionEvaluator, ReversedUDWF, Signature, TypeSignature, Volatility,
+ WindowUDFImpl,
+};
+use datafusion_functions_window_common::field::WindowUDFFieldArgs;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
use std::any::Any;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::{Neg, Range};
use std::sync::Arc;
-/// window shift expression
+get_or_init_udwf!(
+ Lag,
+ lag,
+ "Returns the row value that precedes the current row by a specified \
+ offset within partition. If no such row exists, then returns the \
+ default value.",
+ WindowShift::lag
+);
+get_or_init_udwf!(
+ Lead,
+ lead,
+ "Returns the value from a row that follows the current row by a \
+ specified offset within the partition. If no such row exists, then \
+ returns the default value.",
+ WindowShift::lead
+);
+
+/// Create an expression to represent the `lag` window function
+///
+/// returns value evaluated at the row that is offset rows before the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
Review Comment:
Same as https://github.com/apache/datafusion/blob/a8d3fae21d12a9caafad77a11b8a22bcfe9555fd/datafusion/expr/src/built_in_window_function.rs#L47-L51
##########
datafusion/functions-window/src/lead_lag.rs:
##########
@@ -15,125 +15,200 @@
// specific language governing permissions and limitations
// under the License.
-//! Defines physical expression for `lead` and `lag` that can evaluated
-//! at runtime during query execution
-use crate::window::BuiltInWindowFunctionExpr;
-use crate::PhysicalExpr;
-use arrow::array::ArrayRef;
-use arrow::datatypes::{DataType, Field};
-use arrow_array::Array;
+//! `lead` and `lag` window function implementations
+
+use crate::utils::{get_casted_value, get_scalar_value_from_args, get_signed_integer};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{arrow_datafusion_err, DataFusionError, Result, ScalarValue};
-use datafusion_expr::PartitionEvaluator;
+use datafusion_expr::{
+ Literal, PartitionEvaluator, ReversedUDWF, Signature, TypeSignature, Volatility,
+ WindowUDFImpl,
+};
+use datafusion_functions_window_common::field::WindowUDFFieldArgs;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
use std::any::Any;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::{Neg, Range};
use std::sync::Arc;
-/// window shift expression
+get_or_init_udwf!(
+ Lag,
+ lag,
+ "Returns the row value that precedes the current row by a specified \
+ offset within partition. If no such row exists, then returns the \
+ default value.",
+ WindowShift::lag
+);
+get_or_init_udwf!(
+ Lead,
+ lead,
+ "Returns the value from a row that follows the current row by a \
+ specified offset within the partition. If no such row exists, then \
+ returns the default value.",
+ WindowShift::lead
+);
+
+/// Create an expression to represent the `lag` window function
+///
+/// returns value evaluated at the row that is offset rows before the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
Review Comment:
Same as https://github.com/apache/datafusion/blob/a8d3fae21d12a9caafad77a11b8a22bcfe9555fd/datafusion/expr/src/built_in_window_function.rs#L47-L51
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797735004
##########
datafusion/proto/src/logical_plan/from_proto.rs:
##########
@@ -286,10 +284,7 @@ pub fn parse_expr(
.map_err(|_| Error::unknown("BuiltInWindowFunction", *i))?
.into();
- let args =
- parse_optional_expr(expr.expr.as_deref(), registry, codec)?
- .map(|e| vec![e])
- .unwrap_or_else(Vec::new);
+ let args = parse_exprs(&expr.exprs, registry, codec)?;
Review Comment:
Parse all arguments instead of parsing only the first argument.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2417036918
I merged this branch up to resolve some conflicts (due to https://github.com/apache/datafusion/pull/12893)
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2417718509
Or maybe you could just make the change in this PR - the downside of merging this is that it reintroduces a bug (temporarily). I think given we are planning the 43 release https://github.com/apache/datafusion/issues/12470 in the next few days it would be nice to avoid breaking a previous bug fix
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797691460
##########
datafusion/functions-window/src/lead_lag.rs:
##########
@@ -15,125 +15,200 @@
// specific language governing permissions and limitations
// under the License.
-//! Defines physical expression for `lead` and `lag` that can evaluated
-//! at runtime during query execution
-use crate::window::BuiltInWindowFunctionExpr;
-use crate::PhysicalExpr;
-use arrow::array::ArrayRef;
-use arrow::datatypes::{DataType, Field};
-use arrow_array::Array;
+//! `lead` and `lag` window function implementations
+
+use crate::utils::{get_casted_value, get_scalar_value_from_args, get_signed_integer};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{arrow_datafusion_err, DataFusionError, Result, ScalarValue};
-use datafusion_expr::PartitionEvaluator;
+use datafusion_expr::{
+ Literal, PartitionEvaluator, ReversedUDWF, Signature, TypeSignature, Volatility,
+ WindowUDFImpl,
+};
+use datafusion_functions_window_common::field::WindowUDFFieldArgs;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
use std::any::Any;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::{Neg, Range};
use std::sync::Arc;
-/// window shift expression
+get_or_init_udwf!(
+ Lag,
+ lag,
+ "Returns the row value that precedes the current row by a specified \
+ offset within partition. If no such row exists, then returns the \
+ default value.",
+ WindowShift::lag
+);
+get_or_init_udwf!(
+ Lead,
+ lead,
+ "Returns the value from a row that follows the current row by a \
+ specified offset within the partition. If no such row exists, then \
+ returns the default value.",
+ WindowShift::lead
+);
+
+/// Create an expression to represent the `lag` window function
+///
+/// returns value evaluated at the row that is offset rows before the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lag(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lag_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
+/// Create an expression to represent the `lead` window function
+///
+/// returns value evaluated at the row that is offset rows after the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lead(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lead_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
#[derive(Debug)]
-pub struct WindowShift {
- name: String,
- /// Output data type
- data_type: DataType,
- shift_offset: i64,
- expr: Arc<dyn PhysicalExpr>,
- default_value: ScalarValue,
- ignore_nulls: bool,
+enum WindowShiftKind {
+ Lag,
+ Lead,
}
-impl WindowShift {
- /// Get shift_offset of window shift expression
- pub fn get_shift_offset(&self) -> i64 {
- self.shift_offset
+impl WindowShiftKind {
+ fn name(&self) -> &'static str {
+ match self {
+ WindowShiftKind::Lag => "lag",
+ WindowShiftKind::Lead => "lead",
+ }
}
- /// Get the default_value for window shift expression.
- pub fn get_default_value(&self) -> ScalarValue {
- self.default_value.clone()
+ /// In [`WindowShiftEvaluator`] a positive offset is used to signal
+ /// computation of `lag()`. So here we negate the input offset
+ /// value when computing `lead()`.
+ fn shift_offset(&self, value: Option<i64>) -> i64 {
+ match self {
+ WindowShiftKind::Lag => value.unwrap_or(1),
+ WindowShiftKind::Lead => value.map(|v| v.neg()).unwrap_or(-1),
+ }
}
}
-/// lead() window function
-pub fn lead(
- name: String,
- data_type: DataType,
- expr: Arc<dyn PhysicalExpr>,
- shift_offset: Option<i64>,
- default_value: ScalarValue,
- ignore_nulls: bool,
-) -> WindowShift {
- WindowShift {
- name,
- data_type,
- shift_offset: shift_offset.map(|v| v.neg()).unwrap_or(-1),
- expr,
- default_value,
- ignore_nulls,
- }
+/// window shift expression
+#[derive(Debug)]
+pub struct WindowShift {
+ signature: Signature,
+ kind: WindowShiftKind,
}
-/// lag() window function
-pub fn lag(
- name: String,
- data_type: DataType,
- expr: Arc<dyn PhysicalExpr>,
- shift_offset: Option<i64>,
- default_value: ScalarValue,
- ignore_nulls: bool,
-) -> WindowShift {
- WindowShift {
- name,
- data_type,
- shift_offset: shift_offset.unwrap_or(1),
- expr,
- default_value,
- ignore_nulls,
+impl WindowShift {
+ fn new(kind: WindowShiftKind) -> Self {
+ Self {
+ signature: Signature::one_of(
+ vec![
+ TypeSignature::Any(1),
+ TypeSignature::Any(2),
+ TypeSignature::Any(3),
+ ],
+ Volatility::Immutable,
+ ),
+ kind,
+ }
+ }
+
+ pub fn lag() -> Self {
+ Self::new(WindowShiftKind::Lag)
+ }
+
+ pub fn lead() -> Self {
+ Self::new(WindowShiftKind::Lead)
}
}
-impl BuiltInWindowFunctionExpr for WindowShift {
- /// Return a reference to Any that can be used for downcasting
+impl WindowUDFImpl for WindowShift {
fn as_any(&self) -> &dyn Any {
self
}
- fn field(&self) -> Result<Field> {
- let nullable = true;
- Ok(Field::new(&self.name, self.data_type.clone(), nullable))
+ fn name(&self) -> &str {
+ self.kind.name()
}
- fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
- vec![Arc::clone(&self.expr)]
+ fn signature(&self) -> &Signature {
+ &self.signature
}
- fn name(&self) -> &str {
- &self.name
- }
+ fn partition_evaluator(
+ &self,
+ partition_evaluator_args: PartitionEvaluatorArgs,
+ ) -> Result<Box<dyn PartitionEvaluator>> {
+ let shift_offset =
+ get_scalar_value_from_args(partition_evaluator_args.input_exprs(), 1)?
+ .map(get_signed_integer)
+ .map_or(Ok(None), |v| v.map(Some))
+ .map(|n| self.kind.shift_offset(n))
+ .map(|offset| {
+ if partition_evaluator_args.is_reversed() {
+ -offset
+ } else {
+ offset
+ }
+ })?;
+ let return_type = partition_evaluator_args
+ .input_types()
+ .first()
+ .unwrap_or(&DataType::Null);
+ let default_value = get_casted_value(
+ get_scalar_value_from_args(partition_evaluator_args.input_exprs(), 2)?,
+ return_type,
+ )?;
- fn create_evaluator(&self) -> Result<Box<dyn PartitionEvaluator>> {
Ok(Box::new(WindowShiftEvaluator {
- shift_offset: self.shift_offset,
- default_value: self.default_value.clone(),
- ignore_nulls: self.ignore_nulls,
+ shift_offset,
+ default_value,
+ ignore_nulls: partition_evaluator_args.ignore_nulls(),
non_null_offsets: VecDeque::new(),
}))
}
- fn reverse_expr(&self) -> Option<Arc<dyn BuiltInWindowFunctionExpr>> {
- Some(Arc::new(Self {
- name: self.name.clone(),
- data_type: self.data_type.clone(),
- shift_offset: -self.shift_offset,
- expr: Arc::clone(&self.expr),
- default_value: self.default_value.clone(),
- ignore_nulls: self.ignore_nulls,
- }))
+ fn field(&self, field_args: WindowUDFFieldArgs) -> Result<Field> {
+ Ok(Field::new(
+ field_args.name(),
+ field_args.get_input_type(0).unwrap(),
+ true,
+ ))
+ }
+
+ fn reverse_expr(&self) -> ReversedUDWF {
+ match self.kind {
+ WindowShiftKind::Lag => ReversedUDWF::Reversed(lag_udwf()),
+ WindowShiftKind::Lead => ReversedUDWF::Reversed(lead_udwf()),
+ }
Review Comment:
- https://github.com/apache/datafusion/pull/12662
This pathway is now tested by sqllogictests.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797694362
##########
datafusion/proto/proto/datafusion.proto:
##########
@@ -526,7 +526,7 @@ message WindowExprNode {
string udaf = 3;
string udwf = 9;
}
- LogicalExprNode expr = 4;
+ repeated LogicalExprNode exprs = 4;
Review Comment:
**<ins>This change is not backwards compatible!</ins>**
- Adds `repeated` keyword to convert to `Vec<LogicalExprNode>`
- Renames from `expr` to `exprs`
This is necessary to correctly serialize expression functions like `lag(col("a"), Some(2), Some(100))` which has more than 1 argument.
Otherwise it gets serialized into `lag(col("a"))` ignoring the second, and third arguments and results in a `SchemaError::FieldNotFound` error when deserialized.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2411093666
Fixed merge conflicts from `main` branch.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797116039
##########
datafusion/functions-window/src/lead_lag.rs:
##########
@@ -15,125 +15,200 @@
// specific language governing permissions and limitations
// under the License.
-//! Defines physical expression for `lead` and `lag` that can evaluated
-//! at runtime during query execution
-use crate::window::BuiltInWindowFunctionExpr;
-use crate::PhysicalExpr;
-use arrow::array::ArrayRef;
-use arrow::datatypes::{DataType, Field};
-use arrow_array::Array;
+//! `lead` and `lag` window function implementations
+
+use crate::utils::{get_casted_value, get_scalar_value_from_args, get_signed_integer};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{arrow_datafusion_err, DataFusionError, Result, ScalarValue};
-use datafusion_expr::PartitionEvaluator;
+use datafusion_expr::{
+ Literal, PartitionEvaluator, ReversedUDWF, Signature, TypeSignature, Volatility,
+ WindowUDFImpl,
+};
+use datafusion_functions_window_common::field::WindowUDFFieldArgs;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
use std::any::Any;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::{Neg, Range};
use std::sync::Arc;
-/// window shift expression
+get_or_init_udwf!(
+ Lag,
+ lag,
+ "Returns the row value that precedes the current row by a specified \
+ offset within partition. If no such row exists, then returns the \
+ default value.",
+ WindowShift::lag
+);
+get_or_init_udwf!(
+ Lead,
+ lead,
+ "Returns the value from a row that follows the current row by a \
+ specified offset within the partition. If no such row exists, then \
+ returns the default value.",
+ WindowShift::lead
+);
+
+/// Create an expression to represent the `lag` window function
+///
+/// returns value evaluated at the row that is offset rows before the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lag(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lag_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
+/// Create an expression to represent the `lead` window function
+///
+/// returns value evaluated at the row that is offset rows after the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lead(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lead_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
#[derive(Debug)]
-pub struct WindowShift {
- name: String,
- /// Output data type
- data_type: DataType,
- shift_offset: i64,
- expr: Arc<dyn PhysicalExpr>,
- default_value: ScalarValue,
- ignore_nulls: bool,
+enum WindowShiftKind {
+ Lag,
+ Lead,
}
-impl WindowShift {
- /// Get shift_offset of window shift expression
- pub fn get_shift_offset(&self) -> i64 {
- self.shift_offset
+impl WindowShiftKind {
+ fn name(&self) -> &'static str {
+ match self {
+ WindowShiftKind::Lag => "lag",
+ WindowShiftKind::Lead => "lead",
+ }
}
- /// Get the default_value for window shift expression.
- pub fn get_default_value(&self) -> ScalarValue {
- self.default_value.clone()
+ /// In [`WindowShiftEvaluator`] a positive offset is used to signal
+ /// computation of `lag()`. So here we negate the input offset
+ /// value for computing `lead()`.
+ fn shift_offset(&self, value: Option<i64>) -> i64 {
+ match self {
+ WindowShiftKind::Lag => value.unwrap_or(1),
+ WindowShiftKind::Lead => value.map(|v| v.neg()).unwrap_or(-1),
+ }
}
}
-/// lead() window function
-pub fn lead(
- name: String,
- data_type: DataType,
- expr: Arc<dyn PhysicalExpr>,
- shift_offset: Option<i64>,
- default_value: ScalarValue,
- ignore_nulls: bool,
-) -> WindowShift {
- WindowShift {
- name,
- data_type,
- shift_offset: shift_offset.map(|v| v.neg()).unwrap_or(-1),
- expr,
- default_value,
- ignore_nulls,
- }
+/// window shift expression
+#[derive(Debug)]
+pub struct WindowShift {
+ signature: Signature,
+ kind: WindowShiftKind,
}
-/// lag() window function
-pub fn lag(
- name: String,
- data_type: DataType,
- expr: Arc<dyn PhysicalExpr>,
- shift_offset: Option<i64>,
- default_value: ScalarValue,
- ignore_nulls: bool,
-) -> WindowShift {
- WindowShift {
- name,
- data_type,
- shift_offset: shift_offset.unwrap_or(1),
- expr,
- default_value,
- ignore_nulls,
+impl WindowShift {
+ fn new(kind: WindowShiftKind) -> Self {
+ Self {
+ signature: Signature::one_of(
+ vec![
+ TypeSignature::Any(1),
+ TypeSignature::Any(2),
+ TypeSignature::Any(3),
+ ],
+ Volatility::Immutable,
+ ),
+ kind,
+ }
+ }
+
+ pub fn lag() -> Self {
+ Self::new(WindowShiftKind::Lag)
+ }
+
+ pub fn lead() -> Self {
+ Self::new(WindowShiftKind::Lead)
}
}
-impl BuiltInWindowFunctionExpr for WindowShift {
- /// Return a reference to Any that can be used for downcasting
+impl WindowUDFImpl for WindowShift {
fn as_any(&self) -> &dyn Any {
self
}
- fn field(&self) -> Result<Field> {
- let nullable = true;
- Ok(Field::new(&self.name, self.data_type.clone(), nullable))
+ fn name(&self) -> &str {
+ self.kind.name()
}
- fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
- vec![Arc::clone(&self.expr)]
+ fn signature(&self) -> &Signature {
+ &self.signature
}
- fn name(&self) -> &str {
- &self.name
- }
+ fn partition_evaluator(
+ &self,
+ partition_evaluator_args: PartitionEvaluatorArgs,
+ ) -> Result<Box<dyn PartitionEvaluator>> {
+ let shift_offset =
+ get_scalar_value_from_args(partition_evaluator_args.input_exprs(), 1)?
+ .map(get_signed_integer)
+ .map_or(Ok(None), |v| v.map(Some))
+ .map(|n| self.kind.shift_offset(n))
+ .map(|offset| {
+ if partition_evaluator_args.is_reversed() {
+ -offset
+ } else {
+ offset
+ }
+ })?;
+ let return_type = partition_evaluator_args
+ .input_types()
+ .first()
+ .unwrap_or(&DataType::Null);
+ let default_value = get_casted_value(
+ get_scalar_value_from_args(partition_evaluator_args.input_exprs(), 2)?,
+ return_type,
+ )?;
Review Comment:
Parse `shift_offset`, `default_value` arguments remains the same as how it is done in built-in window functions.
https://github.com/apache/datafusion/blob/a8d3fae21d12a9caafad77a11b8a22bcfe9555fd/datafusion/physical-plan/src/windows/mod.rs#L254-L285
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2417308020
> @alamb Before we merge this PR, I think it will be better to merge the bug fix done in `BuiltInWindowFunction::{Lead,Lag}` here:
>
> * [Fix: handle NULL input in lead/lag window functionย #12811](https://github.com/apache/datafusion/pull/12811)
>
> I can port the bug fix over to this same PR after #12811 is merged. After that we can merge this to main.
>
> Is that ok?
Sounds like a plan. I just merged #12811 -- just let me know when this PR is ready
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797116039
##########
datafusion/functions-window/src/lead_lag.rs:
##########
@@ -15,125 +15,200 @@
// specific language governing permissions and limitations
// under the License.
-//! Defines physical expression for `lead` and `lag` that can evaluated
-//! at runtime during query execution
-use crate::window::BuiltInWindowFunctionExpr;
-use crate::PhysicalExpr;
-use arrow::array::ArrayRef;
-use arrow::datatypes::{DataType, Field};
-use arrow_array::Array;
+//! `lead` and `lag` window function implementations
+
+use crate::utils::{get_casted_value, get_scalar_value_from_args, get_signed_integer};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{arrow_datafusion_err, DataFusionError, Result, ScalarValue};
-use datafusion_expr::PartitionEvaluator;
+use datafusion_expr::{
+ Literal, PartitionEvaluator, ReversedUDWF, Signature, TypeSignature, Volatility,
+ WindowUDFImpl,
+};
+use datafusion_functions_window_common::field::WindowUDFFieldArgs;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
use std::any::Any;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::{Neg, Range};
use std::sync::Arc;
-/// window shift expression
+get_or_init_udwf!(
+ Lag,
+ lag,
+ "Returns the row value that precedes the current row by a specified \
+ offset within partition. If no such row exists, then returns the \
+ default value.",
+ WindowShift::lag
+);
+get_or_init_udwf!(
+ Lead,
+ lead,
+ "Returns the value from a row that follows the current row by a \
+ specified offset within the partition. If no such row exists, then \
+ returns the default value.",
+ WindowShift::lead
+);
+
+/// Create an expression to represent the `lag` window function
+///
+/// returns value evaluated at the row that is offset rows before the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lag(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lag_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
+/// Create an expression to represent the `lead` window function
+///
+/// returns value evaluated at the row that is offset rows after the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
+pub fn lead(
+ arg: datafusion_expr::Expr,
+ shift_offset: Option<i64>,
+ default_value: Option<ScalarValue>,
+) -> datafusion_expr::Expr {
+ let shift_offset_lit = shift_offset
+ .map(|v| v.lit())
+ .unwrap_or(ScalarValue::Null.lit());
+ let default_lit = default_value.unwrap_or(ScalarValue::Null).lit();
+
+ lead_udwf().call(vec![arg, shift_offset_lit, default_lit])
+}
+
#[derive(Debug)]
-pub struct WindowShift {
- name: String,
- /// Output data type
- data_type: DataType,
- shift_offset: i64,
- expr: Arc<dyn PhysicalExpr>,
- default_value: ScalarValue,
- ignore_nulls: bool,
+enum WindowShiftKind {
+ Lag,
+ Lead,
}
-impl WindowShift {
- /// Get shift_offset of window shift expression
- pub fn get_shift_offset(&self) -> i64 {
- self.shift_offset
+impl WindowShiftKind {
+ fn name(&self) -> &'static str {
+ match self {
+ WindowShiftKind::Lag => "lag",
+ WindowShiftKind::Lead => "lead",
+ }
}
- /// Get the default_value for window shift expression.
- pub fn get_default_value(&self) -> ScalarValue {
- self.default_value.clone()
+ /// In [`WindowShiftEvaluator`] a positive offset is used to signal
+ /// computation of `lag()`. So here we negate the input offset
+ /// value for computing `lead()`.
+ fn shift_offset(&self, value: Option<i64>) -> i64 {
+ match self {
+ WindowShiftKind::Lag => value.unwrap_or(1),
+ WindowShiftKind::Lead => value.map(|v| v.neg()).unwrap_or(-1),
+ }
}
}
-/// lead() window function
-pub fn lead(
- name: String,
- data_type: DataType,
- expr: Arc<dyn PhysicalExpr>,
- shift_offset: Option<i64>,
- default_value: ScalarValue,
- ignore_nulls: bool,
-) -> WindowShift {
- WindowShift {
- name,
- data_type,
- shift_offset: shift_offset.map(|v| v.neg()).unwrap_or(-1),
- expr,
- default_value,
- ignore_nulls,
- }
+/// window shift expression
+#[derive(Debug)]
+pub struct WindowShift {
+ signature: Signature,
+ kind: WindowShiftKind,
}
-/// lag() window function
-pub fn lag(
- name: String,
- data_type: DataType,
- expr: Arc<dyn PhysicalExpr>,
- shift_offset: Option<i64>,
- default_value: ScalarValue,
- ignore_nulls: bool,
-) -> WindowShift {
- WindowShift {
- name,
- data_type,
- shift_offset: shift_offset.unwrap_or(1),
- expr,
- default_value,
- ignore_nulls,
+impl WindowShift {
+ fn new(kind: WindowShiftKind) -> Self {
+ Self {
+ signature: Signature::one_of(
+ vec![
+ TypeSignature::Any(1),
+ TypeSignature::Any(2),
+ TypeSignature::Any(3),
+ ],
+ Volatility::Immutable,
+ ),
+ kind,
+ }
+ }
+
+ pub fn lag() -> Self {
+ Self::new(WindowShiftKind::Lag)
+ }
+
+ pub fn lead() -> Self {
+ Self::new(WindowShiftKind::Lead)
}
}
-impl BuiltInWindowFunctionExpr for WindowShift {
- /// Return a reference to Any that can be used for downcasting
+impl WindowUDFImpl for WindowShift {
fn as_any(&self) -> &dyn Any {
self
}
- fn field(&self) -> Result<Field> {
- let nullable = true;
- Ok(Field::new(&self.name, self.data_type.clone(), nullable))
+ fn name(&self) -> &str {
+ self.kind.name()
}
- fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
- vec![Arc::clone(&self.expr)]
+ fn signature(&self) -> &Signature {
+ &self.signature
}
- fn name(&self) -> &str {
- &self.name
- }
+ fn partition_evaluator(
+ &self,
+ partition_evaluator_args: PartitionEvaluatorArgs,
+ ) -> Result<Box<dyn PartitionEvaluator>> {
+ let shift_offset =
+ get_scalar_value_from_args(partition_evaluator_args.input_exprs(), 1)?
+ .map(get_signed_integer)
+ .map_or(Ok(None), |v| v.map(Some))
+ .map(|n| self.kind.shift_offset(n))
+ .map(|offset| {
+ if partition_evaluator_args.is_reversed() {
+ -offset
+ } else {
+ offset
+ }
+ })?;
+ let return_type = partition_evaluator_args
+ .input_types()
+ .first()
+ .unwrap_or(&DataType::Null);
+ let default_value = get_casted_value(
+ get_scalar_value_from_args(partition_evaluator_args.input_exprs(), 2)?,
+ return_type,
+ )?;
Review Comment:
Parse `shift_offset`, `default_value` arguments is same as how it is done in built-in window functions.
https://github.com/apache/datafusion/blob/a8d3fae21d12a9caafad77a11b8a22bcfe9555fd/datafusion/physical-plan/src/windows/mod.rs#L254-L285
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797693389
##########
datafusion/functions-window/src/utils.rs:
##########
Review Comment:
These helper functions are needed for parsing the `lead` and `lag` window function arguments. So they are copied from `datafusion/physical-plan/src/windows/mod.rs`.
Temporarily there is duplication because we cannot depend on `functions-window` in `physical-plan` because of cyclic dependency.
- after #12694 is converted `get_scalar_value_from_args` can be removed from `physical-plan`.
- after #12649 is converted `get_signed_integer` can be removed from `physical-plan`.
The `get_casted_value` function is already removed from `physical-plan` in this PR.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797694362
##########
datafusion/proto/proto/datafusion.proto:
##########
@@ -526,7 +526,7 @@ message WindowExprNode {
string udaf = 3;
string udwf = 9;
}
- LogicalExprNode expr = 4;
+ repeated LogicalExprNode exprs = 4;
Review Comment:
**<ins>This change is not backwards compatible!</ins>**
This is necessary to correctly serialize expression functions like `lag(col("a"), Some(2), Some(100))` which has more than 1 argument.
Otherwise it gets serialized into `lag(col("a"))` ignoring the second, and third arguments and results in an error when deserialized.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797695084
##########
datafusion/proto/proto/datafusion.proto:
##########
@@ -526,7 +526,7 @@ message WindowExprNode {
string udaf = 3;
string udwf = 9;
}
- LogicalExprNode expr = 4;
+ repeated LogicalExprNode exprs = 4;
Review Comment:
Happy to redo this if not the right way of handling this for downstream DataFusion users.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] wip: Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on code in PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#discussion_r1797686699
##########
datafusion/functions-window/src/lead_lag.rs:
##########
@@ -15,125 +15,200 @@
// specific language governing permissions and limitations
// under the License.
-//! Defines physical expression for `lead` and `lag` that can evaluated
-//! at runtime during query execution
-use crate::window::BuiltInWindowFunctionExpr;
-use crate::PhysicalExpr;
-use arrow::array::ArrayRef;
-use arrow::datatypes::{DataType, Field};
-use arrow_array::Array;
+//! `lead` and `lag` window function implementations
+
+use crate::utils::{get_casted_value, get_scalar_value_from_args, get_signed_integer};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{arrow_datafusion_err, DataFusionError, Result, ScalarValue};
-use datafusion_expr::PartitionEvaluator;
+use datafusion_expr::{
+ Literal, PartitionEvaluator, ReversedUDWF, Signature, TypeSignature, Volatility,
+ WindowUDFImpl,
+};
+use datafusion_functions_window_common::field::WindowUDFFieldArgs;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
use std::any::Any;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::{Neg, Range};
use std::sync::Arc;
-/// window shift expression
+get_or_init_udwf!(
+ Lag,
+ lag,
+ "Returns the row value that precedes the current row by a specified \
+ offset within partition. If no such row exists, then returns the \
+ default value.",
+ WindowShift::lag
+);
+get_or_init_udwf!(
+ Lead,
+ lead,
+ "Returns the value from a row that follows the current row by a \
+ specified offset within the partition. If no such row exists, then \
+ returns the default value.",
+ WindowShift::lead
+);
+
+/// Create an expression to represent the `lag` window function
+///
+/// returns value evaluated at the row that is offset rows before the current row within the partition;
+/// if there is no such row, instead return default (which must be of the same type as value).
+/// Both offset and default are evaluated with respect to the current row.
+/// If omitted, offset defaults to 1 and default to null
Review Comment:
Copied verbatim from built-in window function https://github.com/apache/datafusion/blob/a8d3fae21d12a9caafad77a11b8a22bcfe9555fd/datafusion/expr/src/built_in_window_function.rs#L47-L51
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2414212261
Thanks @alamb ๐
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2420012516
1. Port the bug fix for handling `NULL` input in https://github.com/apache/datafusion/pull/12857/commits/814a9b7ec3d5460bf927ac80e6c5cddb61b5aea1. Made it into a single commit to make it easier to see the isolated diff for the bug fix.
2. Added a few more test cases in https://github.com/apache/datafusion/pull/12857/commits/c4b884098810997e21c1d683a9e3ca4dba2b397f
3. Added `WindowUDFImpl::expressions`. It has a default implementation so does not break existing user-defined window function implementations.
@alamb This is ready for review again.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Convert `BuiltInWindowFunction::{Lead, Lag}` to a user defined window function [datafusion]
Posted by "jcsherin (via GitHub)" <gi...@apache.org>.
jcsherin commented on PR #12857:
URL: https://github.com/apache/datafusion/pull/12857#issuecomment-2417279951
@alamb Before we merge this PR, I think it will be better to merge the bug fix done in `BuiltInWindowFunction::{Lead,Lag}` here:
- #12811
I can port the bug fix over to this same PR after #12811 is merged. After that we can merge this to main.
Is that ok?
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org