use super::*;
use crate::functions::navigation_common::nullable_navigation_data_type;
use crate::planning::logical::utils::causal_window_frame;
use crate::planning::logical::{
selected_row_filter_expr, sequence_sort_expr, valid_match_row_expr,
};
use datafusion::common::config::ConfigOptions;
use datafusion::logical_expr::expr::AggregateFunctionParams;
use datafusion::logical_expr::simplify::SimplifyContext;
use datafusion::optimizer::simplify_expressions::ExprSimplifier;
pub(crate) fn simplified_literal(expr: &Expr, options: &ConfigOptions) -> Option<Expr> {
if expr.is_volatile() || !expr.column_refs().is_empty() {
return None;
}
let empty_schema = Arc::new(DFSchema::empty());
let context = SimplifyContext::builder()
.with_schema(Arc::clone(&empty_schema))
.with_config_options(Arc::new(options.clone()))
.build();
let simplifier = ExprSimplifier::new(context);
let coerced = simplifier.coerce(expr.clone(), &empty_schema).ok()?;
match simplifier.simplify(coerced).ok()? {
literal @ Expr::Literal(_, _) => Some(literal),
_ => None,
}
}
pub(crate) fn builtin_aggregate_udf(name: &str) -> Option<Arc<AggregateUDF>> {
static DEFAULTS: std::sync::LazyLock<
std::collections::HashMap<String, Arc<AggregateUDF>>,
> = std::sync::LazyLock::new(|| {
let mut by_name = std::collections::HashMap::new();
for udf in datafusion::functions_aggregate::all_default_aggregate_functions() {
for alias in udf.aliases() {
by_name.insert(alias.clone(), Arc::clone(&udf));
}
by_name.insert(udf.name().to_string(), udf);
}
by_name.insert(
"average".to_string(),
datafusion::functions_aggregate::average::avg_udaf(),
);
by_name.insert(
"variance".to_string(),
datafusion::functions_aggregate::variance::var_samp_udaf(),
);
by_name
});
DEFAULTS.get(name).cloned()
}
pub(super) fn first_last_udaf(name: &str) -> Arc<AggregateUDF> {
match name {
"first" => datafusion::functions_aggregate::first_last::first_value_udaf(),
"last" => datafusion::functions_aggregate::first_last::last_value_udaf(),
_ => unreachable!("unsupported FIRST/LAST name"),
}
}
pub(super) fn first_last_offset_udaf(name: &str) -> Arc<AggregateUDF> {
match name {
"first" => crate::functions::udaf::mr_first_offset_udaf(),
"last" => crate::functions::udaf::mr_last_offset_udaf(),
_ => unreachable!("unsupported FIRST/LAST name"),
}
}
pub(super) fn first_last_udwf(name: &str) -> Arc<WindowUDF> {
match name {
"first" => crate::functions::udwf::mr_first_udwf(),
"last" => crate::functions::udwf::mr_last_udwf(),
_ => unreachable!("unsupported FIRST/LAST name"),
}
}
pub(super) fn navigation_udaf(name: &str) -> Arc<AggregateUDF> {
match name {
"prev" => crate::functions::udaf::mr_prev_udaf(),
"next" => crate::functions::udaf::mr_next_udaf(),
_ => unreachable!("unsupported PREV/NEXT name"),
}
}
pub(super) fn mr_navigation_udwf(name: &str) -> Arc<WindowUDF> {
match name {
"prev" => crate::functions::udwf::mr_prev_udwf(),
"next" => crate::functions::udwf::mr_next_udwf(),
_ => unreachable!("unsupported PREV/NEXT name"),
}
}
pub(super) fn standard_navigation_udwf(name: &str) -> Arc<WindowUDF> {
match name {
"prev" => datafusion::functions_window::lead_lag::lag_udwf(),
"next" => datafusion::functions_window::lead_lag::lead_udwf(),
_ => unreachable!("unsupported standard navigation name"),
}
}
pub(super) fn window_expr(
fun: WindowFunctionDefinition,
params: WindowFunctionParams,
) -> Expr {
Expr::WindowFunction(Box::new(WindowFunction { fun, params }))
}
pub(crate) fn canonical_navigation_aggregate_params(
args: Vec<Expr>,
) -> AggregateFunctionParams {
AggregateFunctionParams {
args,
distinct: false,
filter: None,
order_by: vec![sequence_sort_expr()],
null_treatment: None,
}
}
pub(crate) fn canonical_define_navigation_window_params(
partition_by: &[Expr],
args: Vec<Expr>,
) -> WindowFunctionParams {
let mut partition_by = partition_by.to_vec();
partition_by.push(col(MatchMetadataColumn::MatchNumber.as_ref()));
WindowFunctionParams {
args,
partition_by,
order_by: vec![sequence_sort_expr()],
window_frame: causal_window_frame(),
filter: None,
distinct: false,
null_treatment: None,
}
}
pub(super) fn measures_navigation_frame(
name: &str,
offset: NavigationOffset,
) -> WindowFrame {
match name {
"next" => WindowFrame::new_bounds(
WindowFrameUnits::Rows,
WindowFrameBound::Preceding(ScalarValue::UInt64(None)),
if offset.is_zero() {
WindowFrameBound::CurrentRow
} else {
WindowFrameBound::Following(ScalarValue::UInt64(Some(offset.as_u64())))
},
),
_ => causal_window_frame(),
}
}
pub(super) fn partition_navigation_frame(
name: &str,
offset: NavigationOffset,
) -> WindowFrame {
match name {
"next" => WindowFrame::new_bounds(
WindowFrameUnits::Rows,
WindowFrameBound::CurrentRow,
if offset.is_zero() {
WindowFrameBound::CurrentRow
} else {
WindowFrameBound::Following(ScalarValue::UInt64(Some(offset.as_u64())))
},
),
_ => causal_window_frame(),
}
}
pub(crate) fn classifier_mask_expr(symbol: &str) -> Expr {
col(classifier_bits_col_name(symbol))
}
pub(super) fn first_last_unqualified_filter_expr(clause: SourceClause<'_>) -> Expr {
if matches!(
clause,
SourceClause::Measures | SourceClause::ExplicitOutput
) {
selected_row_filter_expr()
} else {
valid_match_row_expr()
}
}
pub(super) fn and_optional_filter(existing: Option<Expr>, extra: Expr) -> Expr {
existing
.map(|filter| nullable_filtered_arg(extra.clone(), filter))
.unwrap_or(extra)
}
pub(super) fn nullable_filtered_arg(filter: Expr, arg: Expr) -> Expr {
Expr::Case(Case::new(
None,
vec![(Box::new(filter), Box::new(arg))],
None,
))
}
pub(super) fn can_replace_filter_with_null(udaf: &AggregateUDF) -> bool {
crate::planning::extract::is_ordinary_aggregate_name(udaf.name())
&& builtin_aggregate_udf(udaf.name())
.is_some_and(|builtin| builtin.as_ref() == udaf)
}
pub(super) fn fold_define_aggregate_filter(
udaf: &AggregateUDF,
user_filter: &Expr,
args: &mut [Expr],
order_by: &mut [SortExpr],
schema: &DFSchema,
) -> bool {
if args.is_empty() || !can_replace_filter_with_null(udaf) {
return false;
}
let needs_nullable_ree = |expr: &Expr| {
expr.get_type(schema)
.is_ok_and(|dt| nullable_navigation_data_type(&dt) != dt)
};
let arg_cannot_wrap_in_case = |expr: &Expr| {
expr.to_field(schema).is_ok_and(|(_, field)| {
nullable_navigation_data_type(field.data_type()) != *field.data_type()
|| !field.metadata().is_empty()
})
};
if args.iter().any(arg_cannot_wrap_in_case) {
return false;
}
let has_observable_order_by = order_by.iter().any(|sort| {
!crate::planning::expr_safety::can_discard_scalar(&sort.expr, Some(schema))
});
if has_observable_order_by
&& order_by.iter().any(|sort| {
!crate::planning::expr_safety::can_discard_scalar(&sort.expr, Some(schema))
&& needs_nullable_ree(&sort.expr)
})
{
return false;
}
if user_filter.is_volatile() && (args.len() > 1 || has_observable_order_by) {
return false;
}
for arg in args {
let value = std::mem::replace(arg, Expr::Literal(ScalarValue::Null, None));
*arg = nullable_filtered_arg(user_filter.clone(), value);
}
if has_observable_order_by {
for sort in order_by {
if !crate::planning::expr_safety::can_discard_scalar(&sort.expr, Some(schema))
{
let value = std::mem::replace(
&mut sort.expr,
Expr::Literal(ScalarValue::Null, None),
);
sort.expr = nullable_filtered_arg(user_filter.clone(), value);
}
}
}
true
}
pub(super) fn single_symbol(
symbols: &BTreeSet<String>,
clause: &str,
construct: &str,
) -> Result<Option<String>> {
if symbols.len() > 1 {
return plan_err!(
"MATCH_RECOGNIZE source {clause} {construct} cannot mix pattern symbols: {symbols:?}"
);
}
Ok(symbols.iter().next().cloned())
}
pub(super) fn single_rpv(
lowered: &LoweredExpr,
clause: &str,
construct: &str,
) -> Result<Option<String>> {
let symbol = single_symbol(&lowered.symbols, clause, construct)?;
if let Some(symbol) = &symbol
&& lowered.has_universal_rpv
{
return plan_err!(
"MATCH_RECOGNIZE source {clause} {construct} cannot mix unqualified and symbol-qualified references (symbol '{symbol}')"
);
}
Ok(symbol)
}
pub(super) fn require_navigation_rpv(
lowered: &LoweredExpr,
clause: &str,
construct: &str,
) -> Result<()> {
if lowered.symbols.is_empty()
&& !lowered.has_universal_rpv
&& !lowered.has_row_metadata
{
return plan_err!(
"MATCH_RECOGNIZE source {clause} {} argument must reference at least one input column or CLASSIFIER()",
construct.to_ascii_uppercase()
);
}
Ok(())
}
pub(super) fn logical_navigation_offset(
expr: Option<&Expr>,
name: &str,
options: &ConfigOptions,
) -> Result<NavigationOffset> {
let Some(expr) = expr else {
return Ok(NavigationOffset::ZERO);
};
let Some(Expr::Literal(value, _)) = simplified_literal(expr, options) else {
return plan_err!(
"{} offset must be a non-null, non-negative exact integer constant",
name.to_ascii_uppercase()
);
};
exact_navigation_offset_literal(
&value,
name,
"a non-null, non-negative exact integer constant",
)
}
fn exact_navigation_offset_literal(
value: &ScalarValue,
name: &str,
requirement: &str,
) -> Result<NavigationOffset> {
let name = name.to_ascii_uppercase();
let invalid = || {
datafusion::common::DataFusionError::Plan(format!(
"{name} offset must be {requirement}"
))
};
let offset = match value {
ScalarValue::Decimal32(Some(v), _, 0) => {
u128::try_from(*v).map_err(|_| invalid())?
}
ScalarValue::Decimal64(Some(v), _, 0) => {
u128::try_from(*v).map_err(|_| invalid())?
}
ScalarValue::Decimal128(Some(v), _, 0) => {
u128::try_from(*v).map_err(|_| invalid())?
}
ScalarValue::Decimal256(Some(v), _, 0) => {
if v.is_negative() {
return Err(invalid());
}
match v.to_i128().and_then(|n| u128::try_from(n).ok()) {
Some(n) => n,
None => {
return plan_err!(
"{name} offset {v} exceeds the maximum supported navigation offset {MAX_NAVIGATION_OFFSET}"
);
}
}
}
other => literal_nonnegative_u64(other)
.map(u128::from)
.ok_or_else(invalid)?,
};
if offset > u128::from(MAX_NAVIGATION_OFFSET) {
return plan_err!(
"{name} offset {offset} exceeds the maximum supported navigation offset {MAX_NAVIGATION_OFFSET}"
);
}
let offset = offset as u64;
NavigationOffset::try_from_u64(offset).ok_or_else(|| {
datafusion::common::DataFusionError::Plan(format!(
"{name} offset {offset} cannot be represented on this execution platform"
))
})
}
pub(super) fn navigation_offset(
expr: Option<&Expr>,
name: &str,
) -> Result<NavigationOffset> {
let Some(expr) = expr else {
return Ok(NavigationOffset::ONE);
};
match expr {
Expr::Literal(value, _) => exact_navigation_offset_literal(
value,
name,
"a non-null, non-negative integer literal",
),
_ => plan_err!(
"{} offset must be a non-null, non-negative integer literal",
name.to_ascii_uppercase()
),
}
}
pub(crate) fn literal_nonnegative_u64(value: &ScalarValue) -> Option<u64> {
match value {
ScalarValue::Int8(Some(value)) => u64::try_from(*value).ok(),
ScalarValue::Int16(Some(value)) => u64::try_from(*value).ok(),
ScalarValue::Int32(Some(value)) => u64::try_from(*value).ok(),
ScalarValue::Int64(Some(value)) => u64::try_from(*value).ok(),
ScalarValue::UInt8(Some(value)) => Some(u64::from(*value)),
ScalarValue::UInt16(Some(value)) => Some(u64::from(*value)),
ScalarValue::UInt32(Some(value)) => Some(u64::from(*value)),
ScalarValue::UInt64(Some(value)) => Some(*value),
_ => None,
}
}
pub(super) fn column_ref(expr: &Expr) -> Result<Column> {
match expr {
Expr::Column(column) => Ok(column.clone()),
_ => plan_err!(
"MATCH_RECOGNIZE source pattern field normalization expected a column expression, got {expr:?}"
),
}
}
pub(super) fn source_clause_name(clause: SourceClause<'_>) -> &'static str {
match clause {
SourceClause::PartitionBy => "PARTITION BY",
SourceClause::OrderBy => "ORDER BY",
SourceClause::Define { .. } => "DEFINE",
SourceClause::Measures => "MEASURES",
SourceClause::ExplicitOutput => "explicit output",
}
}
#[cfg(test)]
mod tests {
use super::{
builtin_aggregate_udf, can_replace_filter_with_null, logical_navigation_offset,
navigation_offset,
};
use crate::core::{MAX_NAVIGATION_OFFSET, NavigationOffset};
use crate::planning::logical::valid_match_row_expr;
use datafusion::arrow::datatypes::i256;
use datafusion::common::{ScalarValue, config::ConfigOptions};
use datafusion::logical_expr::{col, lit};
#[test]
fn navigation_offsets_share_exact_integer_and_decimal_validation() {
let options = ConfigOptions::new();
let cases = [
(ScalarValue::Int64(Some(1)), true),
(ScalarValue::UInt64(Some(1)), true),
(ScalarValue::Decimal32(Some(1), 9, 0), true),
(ScalarValue::Decimal64(Some(1), 18, 0), true),
(ScalarValue::Decimal128(Some(1), 38, 0), true),
(
ScalarValue::Decimal256(Some(i256::from_i128(1)), 76, 0),
true,
),
(ScalarValue::Decimal32(Some(10), 9, 1), false),
(ScalarValue::Decimal64(Some(10), 18, 1), false),
(ScalarValue::Decimal128(Some(10), 38, 1), false),
(
ScalarValue::Decimal256(Some(i256::from_i128(10)), 76, 1),
false,
),
(ScalarValue::Decimal128(Some(1), 38, -1), false),
(ScalarValue::Int64(Some(-1)), false),
(
ScalarValue::Decimal256(Some(i256::from_i128(-1)), 76, 0),
false,
),
(ScalarValue::Float64(Some(1.0)), false),
(ScalarValue::UInt64(Some(MAX_NAVIGATION_OFFSET + 1)), false),
(
ScalarValue::Decimal128(
Some(i128::from(MAX_NAVIGATION_OFFSET) + 1),
38,
0,
),
false,
),
(
ScalarValue::Decimal256(
Some(i256::from_i128(i128::MAX) + i256::from_i128(1)),
76,
0,
),
false,
),
];
for (value, valid) in cases {
let expr = lit(value);
let physical = navigation_offset(Some(&expr), "prev");
let logical = logical_navigation_offset(Some(&expr), "first", &options);
assert_eq!(physical.is_ok(), valid, "{expr:?}: {physical:?}");
assert_eq!(logical.is_ok(), valid, "{expr:?}: {logical:?}");
if valid {
assert_eq!(physical.unwrap(), NavigationOffset::ONE);
assert_eq!(logical.unwrap(), NavigationOffset::ONE);
}
}
}
#[test]
fn navigation_offsets_reject_null_literals() {
let options = ConfigOptions::new();
let cases = [
ScalarValue::Null,
ScalarValue::Int8(None),
ScalarValue::Int16(None),
ScalarValue::Int32(None),
ScalarValue::Int64(None),
ScalarValue::UInt8(None),
ScalarValue::UInt16(None),
ScalarValue::UInt32(None),
ScalarValue::UInt64(None),
ScalarValue::Decimal32(None, 9, 0),
ScalarValue::Decimal64(None, 18, 0),
ScalarValue::Decimal128(None, 38, 0),
ScalarValue::Decimal256(None, 76, 0),
ScalarValue::Decimal32(None, 9, 1),
ScalarValue::Decimal64(None, 18, 1),
ScalarValue::Decimal128(None, 38, 1),
ScalarValue::Decimal256(None, 76, 1),
ScalarValue::Utf8(None),
ScalarValue::Boolean(None),
ScalarValue::Float64(None),
];
for value in cases {
let expr = lit(value);
assert!(navigation_offset(Some(&expr), "prev").is_err(), "{expr:?}");
assert!(navigation_offset(Some(&expr), "next").is_err(), "{expr:?}");
assert!(
logical_navigation_offset(Some(&expr), "first", &options).is_err(),
"{expr:?}"
);
}
}
#[test]
fn filter_null_substitution_requires_known_null_ignoring_identity() {
for (name, expected) in [
("sum", true),
("count", true),
("corr", true),
("array_agg", false),
("first_value", false),
("last_value", false),
] {
let udaf = builtin_aggregate_udf(name).unwrap();
assert_eq!(
can_replace_filter_with_null(udaf.as_ref()),
expected,
"{name}"
);
}
let custom = datafusion::logical_expr::AggregateUDF::from(
crate::planning::expressions::test_support::SameNameCustomAggregate {
name: "sum",
},
);
assert!(!can_replace_filter_with_null(&custom));
}
#[test]
fn valid_match_rows_include_both_exact_metadata_boundaries() {
let sequence = col("__mr_match_sequence_number");
assert_eq!(
valid_match_row_expr(),
sequence
.clone()
.gt_eq(lit(0_i64))
.and(sequence.lt_eq(lit((1_i64 << 62) - 1)))
);
}
#[test]
fn aggregate_resolver_covers_datafusion_defaults_by_exact_identity() {
for expected in datafusion::functions_aggregate::all_default_aggregate_functions()
{
let actual = builtin_aggregate_udf(expected.name())
.unwrap_or_else(|| panic!("missing {}", expected.name()));
assert_eq!(actual.as_ref(), expected.as_ref());
for alias in expected.aliases() {
let actual = builtin_aggregate_udf(alias)
.unwrap_or_else(|| panic!("missing alias {alias}"));
assert_eq!(actual.as_ref(), expected.as_ref(), "alias {alias}");
}
}
}
#[test]
fn aggregate_resolver_keeps_local_aliases_and_exact_keys() {
for (name, expected) in [
(
"average",
datafusion::functions_aggregate::average::avg_udaf(),
),
(
"variance",
datafusion::functions_aggregate::variance::var_samp_udaf(),
),
] {
assert_eq!(
builtin_aggregate_udf(name).unwrap().as_ref(),
expected.as_ref(),
"{name}"
);
}
for rejected in [
"first",
"last",
"prev",
"next",
"__mr_first_agg",
"__mr_last_agg",
"__mr_prev_agg",
"__mr_next_agg",
"FIRST",
"LAST",
"First",
"Last",
"SUM",
"COUNT",
"AVERAGE",
"VARIANCE",
] {
assert!(
builtin_aggregate_udf(rejected).is_none(),
"builtin_aggregate_udf should not resolve '{rejected}'"
);
}
}
#[test]
fn simplified_literal_coerces_arithmetic_functions_and_common_branch_types() {
use datafusion::arrow::datatypes::DataType;
use datafusion::logical_expr::{
Expr,
expr::{Case, Cast},
};
let options = ConfigOptions::default();
for (expr, expected) in [
(lit(1_i64) + lit(0.5_f64), lit(1.5_f64)),
(
Expr::Cast(Cast::new(Box::new(lit(1_i64)), DataType::Int32)) + lit(2_i64),
lit(3_i64),
),
(
datafusion::functions::math::power().call(vec![lit(2_i64), lit(3_i64)]),
lit(8.0_f64),
),
(
datafusion::functions::core::coalesce()
.call(vec![lit(1_i64), lit(2.5_f64)]),
lit(1.0_f64),
),
(
Expr::Case(Case::new(
None,
vec![(Box::new(lit(true)), Box::new(lit(1_i64)))],
Some(Box::new(lit(0.5_f64))),
)),
lit(1.0_f64),
),
] {
assert_eq!(
super::simplified_literal(&expr, &options),
Some(expected),
"{expr}"
);
}
}
#[test]
fn simplified_literal_rejects_column_refs_and_volatile_exprs() {
use datafusion::common::ScalarValue;
use datafusion::common::config::ConfigOptions;
let options = ConfigOptions::default();
assert_eq!(
super::simplified_literal(&(lit(1_i64) + lit(2_i64)), &options),
Some(lit(3_i64)),
);
assert_eq!(
super::simplified_literal(&col("price").is_not_null(), &options),
None,
);
assert_eq!(
super::simplified_literal(
&(lit(ScalarValue::Int64(None)) + col("price")),
&options,
),
None,
);
assert_eq!(
super::simplified_literal(
&datafusion::functions::math::random().call(vec![]),
&options,
),
None,
);
}
#[test]
fn logical_navigation_offset_validates_scale_zero_exact_constants() {
use crate::core::MAX_NAVIGATION_OFFSET;
use datafusion::arrow::datatypes::i256;
use datafusion::common::ScalarValue;
use datafusion::common::config::ConfigOptions;
let options = ConfigOptions::default();
assert_eq!(
logical_navigation_offset(None, "first", &options)
.unwrap()
.as_u64(),
0
);
for (expr, expected) in [
(lit(ScalarValue::Int8(Some(0))), 0_u64),
(lit(ScalarValue::Int16(Some(2))), 2_u64),
(lit(ScalarValue::Int32(Some(3))), 3_u64),
(lit(ScalarValue::Int64(Some(4))), 4_u64),
(lit(ScalarValue::UInt8(Some(5))), 5_u64),
(lit(ScalarValue::UInt16(Some(6))), 6_u64),
(lit(ScalarValue::UInt32(Some(7))), 7_u64),
(lit(ScalarValue::UInt64(Some(8))), 8_u64),
(lit(ScalarValue::Decimal32(Some(9), 9, 0)), 9_u64),
(lit(ScalarValue::Decimal64(Some(10), 18, 0)), 10_u64),
(lit(ScalarValue::Decimal128(Some(11), 10, 0)), 11_u64),
(
lit(ScalarValue::Decimal256(Some(i256::from(12)), 10, 0)),
12_u64,
),
(lit(1_i64) + lit(2_i64), 3_u64),
] {
assert_eq!(
logical_navigation_offset(Some(&expr), "first", &options)
.unwrap_or_else(|e| panic!("expected {expr} to succeed: {e}"))
.as_u64(),
expected,
"{expr}"
);
}
for bad in [
lit(ScalarValue::Null),
lit(ScalarValue::Int64(None)),
lit(ScalarValue::Decimal128(None, 10, 0)),
lit(-1_i64),
lit(ScalarValue::Decimal32(Some(-1), 9, 0)),
lit(ScalarValue::Decimal64(Some(-1), 18, 0)),
lit(ScalarValue::Decimal128(Some(-1), 10, 0)),
lit(ScalarValue::Decimal256(Some(i256::from(-1)), 10, 0)),
lit(ScalarValue::Decimal32(Some(10), 9, 1)),
lit(ScalarValue::Decimal64(Some(10), 18, 1)),
lit(ScalarValue::Decimal128(Some(10), 10, 1)),
lit(ScalarValue::Decimal128(Some(15), 10, 1)),
lit(ScalarValue::Decimal256(Some(i256::from(10)), 10, 1)),
lit(1.0_f64),
lit("1"),
col("price"),
datafusion::functions::math::random().call(vec![]),
lit(ScalarValue::UInt64(Some(MAX_NAVIGATION_OFFSET + 1))),
] {
assert!(
logical_navigation_offset(Some(&bad), "last", &options).is_err(),
"expected {bad} to be rejected"
);
}
}
}