use std::ops::ControlFlow;
use datafusion::common::not_impl_err;
use datafusion::sql::planner::NullOrdering;
use datafusion::sql::sqlparser::ast::visit_expressions;
use super::syntax::*;
use super::*;
impl SqlAdapter<'_> {
pub(super) fn adapt_clause_expr(
&self,
clause: SqlClause,
expr: SQLExpr,
) -> Result<ParsedMatchExpr> {
Ok(self.adapt_expr(clause, strip_outer_parentheses(expr))?.expr)
}
pub(super) fn adapt_expr(
&self,
clause: SqlClause,
expr: SQLExpr,
) -> Result<AdaptedSqlExpr> {
reject_reserved_sql_expr(clause_name(clause), &expr)?;
if matches!(expr, SQLExpr::BinaryOp { .. }) {
return self.adapt_binary_expr(clause, expr);
}
let is_subquery = match &expr {
SQLExpr::InSubquery { .. }
| SQLExpr::Exists { .. }
| SQLExpr::Subquery(_) => true,
SQLExpr::AnyOp { right, .. } | SQLExpr::AllOp { right, .. } => {
matches!(right.as_ref(), SQLExpr::Subquery(_))
}
_ => false,
};
if is_subquery {
return plan_err!(
"MATCH_RECOGNIZE {} expression cannot contain subqueries",
clause_name(clause)
);
}
if matches!(clause, SqlClause::Define | SqlClause::Measures)
&& let SQLExpr::CompoundIdentifier(parts) = &expr
&& let [qualifier, column] = parts.as_slice()
&& let Some(symbol) = self.pattern_symbol(&qualifier.value)
{
return Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::PatternField(ParsedPatternField {
symbol: symbol.to_owned(),
column: column.clone(),
}),
structured: true,
});
}
let original_expr = expr.clone();
match expr {
SQLExpr::Function(func) => self.adapt_function(clause, func),
SQLExpr::Floor {
expr,
field: CeilFloorKind::DateTimeField(DateTimeField::NoDateTime),
} => self.adapt_unary_scalar(clause, original_expr, "floor", *expr),
SQLExpr::Ceil {
expr,
field: CeilFloorKind::DateTimeField(DateTimeField::NoDateTime),
} => self.adapt_unary_scalar(clause, original_expr, "ceil", *expr),
SQLExpr::UnaryOp { op, expr } => {
let expr = self.adapt_expr(clause, *expr)?;
if expr.structured {
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::Unary {
op: sql_unary_operator_to_match(&op)?,
expr: Box::new(expr.expr),
},
structured: true,
})
} else {
Ok(AdaptedSqlExpr::input(original_expr))
}
}
SQLExpr::Case {
operand,
conditions,
else_result,
..
} => {
let mut structured = false;
let expr = operand
.map(|expr| {
let adapted = self.adapt_expr(clause, *expr)?;
structured |= adapted.structured;
Ok::<_, datafusion::common::DataFusionError>(Box::new(
adapted.expr,
))
})
.transpose()?;
let when_then = conditions
.into_iter()
.map(|case_when| {
let when = self.adapt_expr(clause, case_when.condition)?;
let then = self.adapt_expr(clause, case_when.result)?;
structured |= when.structured || then.structured;
Ok((when.expr, then.expr))
})
.collect::<Result<Vec<_>>>()?;
let else_expr = else_result
.map(|expr| {
let adapted = self.adapt_expr(clause, *expr)?;
structured |= adapted.structured;
Ok::<_, datafusion::common::DataFusionError>(Box::new(
adapted.expr,
))
})
.transpose()?;
if structured {
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::Case {
expr,
when_then,
else_expr,
},
structured: true,
})
} else {
Ok(AdaptedSqlExpr::input(original_expr))
}
}
SQLExpr::IsNull(expr) => self.adapt_predicate(
clause,
original_expr,
*expr,
MatchPredicateKind::IsNull,
),
SQLExpr::IsNotNull(expr) => self.adapt_predicate(
clause,
original_expr,
*expr,
MatchPredicateKind::IsNotNull,
),
SQLExpr::IsTrue(expr) => self.adapt_predicate(
clause,
original_expr,
*expr,
MatchPredicateKind::IsTrue,
),
SQLExpr::IsFalse(expr) => self.adapt_predicate(
clause,
original_expr,
*expr,
MatchPredicateKind::IsFalse,
),
SQLExpr::IsUnknown(expr) => self.adapt_predicate(
clause,
original_expr,
*expr,
MatchPredicateKind::IsUnknown,
),
SQLExpr::IsNotTrue(expr) => self.adapt_predicate(
clause,
original_expr,
*expr,
MatchPredicateKind::IsNotTrue,
),
SQLExpr::IsNotFalse(expr) => self.adapt_predicate(
clause,
original_expr,
*expr,
MatchPredicateKind::IsNotFalse,
),
SQLExpr::IsNotUnknown(expr) => self.adapt_predicate(
clause,
original_expr,
*expr,
MatchPredicateKind::IsNotUnknown,
),
SQLExpr::Between {
expr,
negated,
low,
high,
} => {
let expr = self.adapt_expr(clause, *expr)?;
let low = self.adapt_expr(clause, *low)?;
let high = self.adapt_expr(clause, *high)?;
if expr.structured || low.structured || high.structured {
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::Between {
expr: Box::new(expr.expr),
negated,
low: Box::new(low.expr),
high: Box::new(high.expr),
},
structured: true,
})
} else {
Ok(AdaptedSqlExpr::input(original_expr))
}
}
SQLExpr::InList {
expr,
list,
negated,
} => {
let expr = self.adapt_expr(clause, *expr)?;
let mut structured = expr.structured;
let list = list
.into_iter()
.map(|item| {
let item = self.adapt_expr(clause, item)?;
structured |= item.structured;
Ok(item.expr)
})
.collect::<Result<Vec<_>>>()?;
if structured {
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::InList {
expr: Box::new(expr.expr),
list,
negated,
},
structured: true,
})
} else {
Ok(AdaptedSqlExpr::input(original_expr))
}
}
SQLExpr::IsDistinctFrom(left, right)
| SQLExpr::IsNotDistinctFrom(left, right) => {
let op = if matches!(original_expr, SQLExpr::IsDistinctFrom(..)) {
Operator::IsDistinctFrom
} else {
Operator::IsNotDistinctFrom
};
let left = self.adapt_expr(clause, *left)?;
let right = self.adapt_expr(clause, *right)?;
if left.structured || right.structured {
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::Binary {
left: Box::new(left.expr),
op,
right: Box::new(right.expr),
},
structured: true,
})
} else {
Ok(AdaptedSqlExpr::input(original_expr))
}
}
SQLExpr::Like {
expr,
pattern,
escape_char,
..
}
| SQLExpr::ILike {
expr,
pattern,
escape_char,
..
}
| SQLExpr::SimilarTo {
expr,
pattern,
escape_char,
..
} => self.adapt_like(clause, original_expr, *expr, *pattern, escape_char),
SQLExpr::Substring {
expr,
substring_from,
substring_for,
..
} => {
if substring_from.is_none() && substring_for.is_none() {
return plan_err!(
"Substring without for/from is not valid {original_expr:?}"
);
}
let value = self.adapt_expr(clause, *expr)?;
let start = substring_from
.map(|start| self.adapt_expr(clause, *start))
.transpose()?
.unwrap_or_else(|| AdaptedSqlExpr {
expr: ParsedMatchExpr::Literal(ScalarValue::Int64(Some(1))),
structured: false,
});
let length = substring_for
.map(|length| self.adapt_expr(clause, *length))
.transpose()?;
let structured = value.structured
|| start.structured
|| length.as_ref().is_some_and(|length| length.structured);
if !structured {
return Ok(AdaptedSqlExpr::input(original_expr));
}
let mut args = vec![value.expr, start.expr];
if let Some(length) = length {
args.push(length.expr);
}
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::ScalarFunction {
name: BUILTIN_SUBSTRING_NAME.to_string(),
args,
},
structured: true,
})
}
SQLExpr::Cast {
kind: CastKind::Cast | CastKind::DoubleColon,
expr,
data_type,
format: None,
} => {
let expr = self.adapt_expr(clause, *expr)?;
if expr.structured {
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::Cast {
expr: Box::new(expr.expr),
data_type,
},
structured: true,
})
} else {
Ok(AdaptedSqlExpr::input(original_expr))
}
}
SQLExpr::Nested(expr) => {
let adapted = self.adapt_expr(clause, *expr)?;
if !adapted.structured
&& let ParsedMatchExpr::InputExpr(expr) = &adapted.expr
&& !matches!(
expr.as_ref(),
SQLExpr::Identifier(_)
| SQLExpr::CompoundIdentifier(_)
| SQLExpr::Value(_)
)
{
return Ok(AdaptedSqlExpr::input(original_expr));
}
Ok(adapted)
}
expr => {
if self.contains_match_expr(clause, &expr) {
return plan_err!(
"MATCH_RECOGNIZE {} does not support {} with pattern variables or MATCH_RECOGNIZE functions",
clause_name(clause),
expression_form(&expr)
);
}
Ok(AdaptedSqlExpr::input(expr))
}
}
}
fn adapt_like(
&self,
clause: SqlClause,
original: SQLExpr,
expr: SQLExpr,
pattern: SQLExpr,
escape_char: Option<Box<SQLExpr>>,
) -> Result<AdaptedSqlExpr> {
let (negated, case_insensitive, similar, any) = match &original {
SQLExpr::Like { negated, any, .. } => (*negated, false, false, *any),
SQLExpr::ILike { negated, any, .. } => (*negated, true, false, *any),
SQLExpr::SimilarTo { negated, .. } => (*negated, false, true, false),
_ => unreachable!("LIKE adaptation requires a LIKE or SIMILAR TO expression"),
};
if any {
return not_impl_err!("ANY in LIKE expression");
}
let pattern = self.adapt_expr(clause, pattern)?;
let expr = self.adapt_expr(clause, expr)?;
let structured_escape = escape_char
.as_ref()
.is_some_and(|escape| self.contains_match_expr(clause, escape));
if !expr.structured && !pattern.structured && !structured_escape {
return Ok(AdaptedSqlExpr::input(original));
}
let escape_char = match escape_char.map(|expr| *expr) {
Some(SQLExpr::Value(ValueWithSpan {
value: Value::SingleQuotedString(value),
..
})) if value.chars().count() == 1 => value.chars().next(),
Some(value) => {
let operator = if similar { "SIMILAR TO" } else { "LIKE" };
return plan_err!(
"Invalid escape character in {operator} expression. Expected a single character wrapped with single quotes, got {value}"
);
}
None => None,
};
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::Like {
negated,
expr: Box::new(expr.expr),
pattern: Box::new(pattern.expr),
escape_char,
case_insensitive,
similar,
},
structured: true,
})
}
fn contains_match_expr(&self, clause: SqlClause, expr: &SQLExpr) -> bool {
let is_define = matches!(clause, SqlClause::Define);
let in_pattern_scope = matches!(clause, SqlClause::Define | SqlClause::Measures);
visit_expressions(expr, |expr| {
let is_match_expr = match expr {
SQLExpr::CompoundIdentifier(parts) => {
in_pattern_scope
&& parts.len() == 2
&& parts.first().is_some_and(|part| {
self.pattern_symbol(&part.value).is_some()
})
}
SQLExpr::CompoundFieldAccess { root, access_chain } => {
in_pattern_scope
&& self
.compound_field_access_has_pattern_prefix(root, access_chain)
}
SQLExpr::Function(func) => {
let name = function_name(func);
let matcher_function = is_unqualified_function(func)
&& (metadata_function(&name).is_some()
|| matches!(
name.as_str(),
"prev" | "next" | "first" | "last"
));
matcher_function
|| match &func.over {
None => {
is_aggregate_function(self.context, &name)
|| (is_define
&& is_window_function(self.context, &name))
}
Some(WindowType::NamedWindow(_)) => is_define,
Some(WindowType::WindowSpec(spec)) => {
is_define
&& (spec.window_name.is_some()
|| self.define_window_defaults(spec)
!= (false, false, false))
}
}
}
_ => false,
};
if is_match_expr {
ControlFlow::Break(())
} else {
ControlFlow::Continue(())
}
})
.is_break()
}
fn compound_field_access_has_pattern_prefix(
&self,
root: &SQLExpr,
access_chain: &[AccessExpr],
) -> bool {
let SQLExpr::Identifier(qualifier) = root else {
return false;
};
if self.pattern_symbol(&qualifier.value).is_none() {
return false;
}
access_chain
.iter()
.take_while(|access| {
matches!(access, AccessExpr::Dot(SQLExpr::Identifier(_)))
})
.count()
== 1
}
fn adapt_binary_expr(
&self,
clause: SqlClause,
expr: SQLExpr,
) -> Result<AdaptedSqlExpr> {
enum Work {
Visit(Box<SQLExpr>),
Combine(BinaryOperator),
}
enum BinaryValue {
Ordinary {
original: Box<SQLExpr>,
adapted: Option<ParsedMatchExpr>,
},
Structured(ParsedMatchExpr),
}
impl BinaryValue {
fn into_match_expr(self) -> ParsedMatchExpr {
match self {
Self::Ordinary {
original,
adapted: Some(adapted),
} => {
dismantle_sql_expr(*original);
adapted
}
Self::Ordinary {
original,
adapted: None,
} => parsed_input(*original),
Self::Structured(expr) => expr,
}
}
fn dismantle(self) {
match self {
Self::Ordinary { original, adapted } => {
dismantle_sql_expr(*original);
if let Some(adapted) = adapted {
dismantle_parsed_match_expr(adapted);
}
}
Self::Structured(expr) => dismantle_parsed_match_expr(expr),
}
}
}
fn dismantle_work(pending: Vec<Work>, values: Vec<BinaryValue>) {
for work in pending {
if let Work::Visit(expr) = work {
dismantle_sql_expr(*expr);
}
}
for value in values {
value.dismantle();
}
}
let mut pending = vec![Work::Visit(Box::new(expr))];
let mut values: Vec<BinaryValue> = Vec::new();
while let Some(work) = pending.pop() {
match work {
Work::Visit(expr) => match *expr {
SQLExpr::BinaryOp { left, op, right } => {
pending.push(Work::Combine(op));
pending.push(Work::Visit(right));
pending.push(Work::Visit(left));
}
leaf => {
let original_nested =
is_nested_simple_leaf(&leaf).then(|| Box::new(leaf.clone()));
let adapted = match self.adapt_expr(clause, leaf) {
Ok(adapted) => adapted,
Err(err) => {
dismantle_work(pending, values);
return Err(err);
}
};
if adapted.structured {
values.push(BinaryValue::Structured(adapted.expr));
} else if let Some(original) = original_nested {
values.push(BinaryValue::Ordinary {
original,
adapted: Some(adapted.expr),
});
} else if let ParsedMatchExpr::InputExpr(original) = adapted.expr
{
values.push(BinaryValue::Ordinary {
original,
adapted: None,
});
} else {
values.push(BinaryValue::Structured(adapted.expr));
}
}
},
Work::Combine(op) => {
let right = values.pop().expect("visited right operand");
let left = values.pop().expect("visited left operand");
match (left, right) {
(
BinaryValue::Ordinary {
original: left_sql, ..
},
BinaryValue::Ordinary {
original: right_sql,
..
},
) => {
values.push(BinaryValue::Ordinary {
original: Box::new(SQLExpr::BinaryOp {
left: left_sql,
op,
right: right_sql,
}),
adapted: None,
});
}
(left, right) => {
let op = match sql_binary_operator_to_df(&op) {
Ok(op) => op,
Err(err) => {
left.dismantle();
right.dismantle();
dismantle_work(pending, values);
return Err(err);
}
};
values.push(BinaryValue::Structured(
ParsedMatchExpr::Binary {
left: Box::new(left.into_match_expr()),
op,
right: Box::new(right.into_match_expr()),
},
));
}
}
}
}
}
Ok(match values.pop().expect("visited binary expression") {
BinaryValue::Ordinary {
original,
adapted: Some(adapted),
} => {
dismantle_sql_expr(*original);
AdaptedSqlExpr {
expr: adapted,
structured: false,
}
}
BinaryValue::Ordinary {
original,
adapted: None,
} => AdaptedSqlExpr::input(*original),
BinaryValue::Structured(expr) => AdaptedSqlExpr {
expr,
structured: true,
},
})
}
fn adapt_unary_scalar(
&self,
clause: SqlClause,
original: SQLExpr,
name: &str,
arg: SQLExpr,
) -> Result<AdaptedSqlExpr> {
let arg = self.adapt_expr(clause, arg)?;
if !arg.structured {
return Ok(AdaptedSqlExpr::input(original));
}
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::ScalarFunction {
name: name.to_string(),
args: vec![arg.expr],
},
structured: true,
})
}
pub(super) fn adapt_predicate(
&self,
clause: SqlClause,
original: SQLExpr,
expr: SQLExpr,
kind: MatchPredicateKind,
) -> Result<AdaptedSqlExpr> {
let adapted = self.adapt_expr(clause, expr)?;
if !adapted.structured {
return Ok(AdaptedSqlExpr::input(original));
}
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::Predicate {
kind,
expr: Box::new(adapted.expr),
},
structured: true,
})
}
pub(super) fn adapt_function(
&self,
clause: SqlClause,
mut func: Function,
) -> Result<AdaptedSqlExpr> {
let normalized = function_name(&func);
let is_unqualified = is_unqualified_function(&func);
if is_unqualified && let Some(metadata) = metadata_function(&normalized) {
ensure_mr_function_syntax(&func, &normalized)?;
ensure_nullary_function(&func, &normalized)?;
if matches!(clause, SqlClause::PartitionBy | SqlClause::OrderBy) {
return plan_err!(
"MATCH_RECOGNIZE metadata function '{}' is not valid in {}",
normalized,
clause_name(clause)
);
}
return Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::Metadata(metadata),
structured: true,
});
}
let navigation_replacement = match normalized.as_str() {
"lag" => Some("PREV"),
"lead" => Some("NEXT"),
"first_value" => Some("FIRST"),
"last_value" => Some("LAST"),
_ => None,
};
if is_unqualified
&& let Some(replacement) = navigation_replacement
&& is_window_function(self.context, &normalized)
{
if matches!(clause, SqlClause::Measures) {
return plan_err!(
"{} not allowed in MEASURES. Use {} instead.",
normalized.to_ascii_uppercase(),
replacement
);
}
if matches!(clause, SqlClause::PartitionBy | SqlClause::OrderBy) {
return plan_err!(
"MATCH_RECOGNIZE {} function '{}' does not support OVER",
clause_name(clause),
normalized
);
}
func = self.inject_define_window(clause, func)?;
return Ok(AdaptedSqlExpr {
expr: parsed_input(SQLExpr::Function(func)),
structured: true,
});
}
if is_unqualified && matches!(normalized.as_str(), "first" | "last") {
ensure_mr_function_syntax(&func, &normalized)?;
let args = mr_positional_expr_args(&func, &normalized)?;
if args.is_empty() || args.len() > 2 {
return plan_err!(
"{} in MATCH_RECOGNIZE expects one or two arguments",
normalized.to_ascii_uppercase()
);
}
let value = self.adapt_expr(clause, args[0].clone())?;
let offset = args
.get(1)
.map(|expr| {
self.adapt_literal_or_expr(clause, expr.clone())
.map(|e| Box::new(e.expr))
})
.transpose()?;
return Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::Navigation(if normalized == "first" {
MatchNavigation::First {
expr: Box::new(value.expr),
offset,
}
} else {
MatchNavigation::Last {
expr: Box::new(value.expr),
offset,
}
}),
structured: true,
});
}
if is_unqualified && matches!(normalized.as_str(), "prev" | "next") {
ensure_mr_function_syntax(&func, &normalized)?;
let args = mr_positional_expr_args(&func, &normalized)?;
if args.is_empty() || args.len() > 3 {
return plan_err!(
"{} in MATCH_RECOGNIZE expects one to three arguments",
normalized.to_ascii_uppercase()
);
}
let value = self.adapt_expr(clause, args[0].clone())?;
let offset = args
.get(1)
.map(|expr| {
self.adapt_literal_or_expr(clause, expr.clone())
.map(|e| Box::new(e.expr))
})
.transpose()?;
let default = args
.get(2)
.map(|expr| {
self.adapt_expr(clause, expr.clone())
.map(|e| Box::new(e.expr))
})
.transpose()?;
return Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::Navigation(if normalized == "prev" {
MatchNavigation::Prev {
expr: Box::new(value.expr),
offset,
default,
}
} else {
MatchNavigation::Next {
expr: Box::new(value.expr),
offset,
default,
}
}),
structured: true,
});
}
if is_aggregate_function(self.context, &normalized)
&& matches!(clause, SqlClause::Define)
&& func.over.is_some()
{
func = self.inject_define_window(clause, func)?;
return Ok(AdaptedSqlExpr {
expr: parsed_input(SQLExpr::Function(func)),
structured: true,
});
}
if is_aggregate_function(self.context, &normalized) {
return self.adapt_aggregate(clause, normalized, func);
}
if is_window_function(self.context, &normalized) {
if matches!(clause, SqlClause::Measures) {
return plan_err!(
"Standard window function {} not allowed in MEASURES. Use MATCH_RECOGNIZE-specific functions instead.",
normalized.to_ascii_uppercase()
);
}
if matches!(clause, SqlClause::PartitionBy | SqlClause::OrderBy) {
return plan_err!(
"MATCH_RECOGNIZE {} function '{}' does not support OVER",
clause_name(clause),
normalized
);
}
func = self.inject_define_window(clause, func)?;
return Ok(AdaptedSqlExpr {
expr: parsed_input(SQLExpr::Function(func)),
structured: true,
});
}
if func.over.is_some() {
return plan_err!(
"MATCH_RECOGNIZE {} function '{}' does not support OVER",
clause_name(clause),
normalized
);
}
if let FunctionArguments::List(list) = &func.args
&& list.clauses.is_empty()
&& list
.args
.iter()
.any(|arg| !matches!(arg, FunctionArg::Unnamed(_)))
{
let unsupported = || {
datafusion::common::DataFusionError::Plan(format!(
"MATCH_RECOGNIZE function '{}' only supports positional expression arguments with matcher expressions",
func.name
))
};
for arg in &list.args {
let arg = match arg {
FunctionArg::Named { arg, .. } | FunctionArg::Unnamed(arg) => arg,
FunctionArg::ExprNamed { name, arg, .. } => {
if self.contains_match_expr(clause, name) {
return Err(unsupported());
}
arg
}
};
let FunctionArgExpr::Expr(expr) = arg else {
return Err(unsupported());
};
if self.adapt_expr(clause, expr.clone())?.structured {
return Err(unsupported());
}
}
return Ok(AdaptedSqlExpr::input(SQLExpr::Function(func)));
}
let original = SQLExpr::Function(func.clone());
let args = positional_expr_args(&func)?;
let mut structured = false;
let args = args
.into_iter()
.map(|arg| {
let arg = self.adapt_expr(clause, arg)?;
structured |= arg.structured;
Ok(arg.expr)
})
.collect::<Result<Vec<_>>>()?;
if structured {
ensure_mr_function_syntax(&func, &normalized)?;
if let FunctionArguments::List(list) = &func.args
&& list.duplicate_treatment.is_some()
{
return plan_err!(
"MATCH_RECOGNIZE scalar function '{}' does not support duplicate treatment with MATCH_RECOGNIZE source expressions",
func.name
);
}
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::ScalarFunction {
name: normalized,
args,
},
structured: true,
})
} else {
Ok(AdaptedSqlExpr::input(original))
}
}
pub(super) fn adapt_aggregate(
&self,
clause: SqlClause,
name: String,
func: Function,
) -> Result<AdaptedSqlExpr> {
if matches!(clause, SqlClause::PartitionBy | SqlClause::OrderBy) {
return plan_err!(
"MATCH_RECOGNIZE aggregate '{}' is not valid in {}",
name,
clause_name(clause)
);
}
if func.over.is_some() {
return plan_err!(
"MATCH_RECOGNIZE aggregate window '{}' is not supported in {}",
name,
clause_name(clause)
);
}
if !function_arguments_are_empty(&func.parameters) {
return plan_err!(
"MATCH_RECOGNIZE aggregate '{}' does not support function parameters",
name
);
}
let FunctionArguments::List(arg_list) = &func.args else {
return plan_err!(
"MATCH_RECOGNIZE aggregate '{}' requires a parenthesized argument list",
name
);
};
let distinct = matches!(
arg_list.duplicate_treatment,
Some(DuplicateTreatment::Distinct)
);
let mut args = Vec::new();
let mut wildcard_symbol = None;
for arg in &arg_list.args {
match arg {
FunctionArg::Unnamed(FunctionArgExpr::Expr(expr)) => {
args.push(self.adapt_expr(clause, expr.clone())?.expr);
}
FunctionArg::Unnamed(FunctionArgExpr::Wildcard) => {
if !name.eq_ignore_ascii_case("count") {
return plan_err!(
"MATCH_RECOGNIZE aggregate '{}(*)' is only supported for COUNT",
name
);
}
if distinct {
return plan_err!(
"MATCH_RECOGNIZE aggregate 'COUNT(DISTINCT *)' is not supported"
);
}
if arg_list.args.len() != 1 {
return plan_err!(
"MATCH_RECOGNIZE aggregate 'COUNT(*)' cannot combine wildcard with other arguments"
);
}
args.push(parsed_input(SQLExpr::Value(
Value::Number("1".to_string(), false).into(),
)));
}
FunctionArg::Unnamed(FunctionArgExpr::QualifiedWildcard(prefix)) => {
if !name.eq_ignore_ascii_case("count") {
return plan_err!(
"MATCH_RECOGNIZE aggregate '{}({}.*)' is only supported for COUNT",
name,
prefix
);
}
let qualifier = single_part_object_name(prefix)?;
if let Some(symbol) = self.pattern_symbol(&qualifier) {
if distinct {
return plan_err!(
"MATCH_RECOGNIZE aggregate 'COUNT(DISTINCT {}.*)' is not supported",
qualifier
);
}
if wildcard_symbol.is_some() {
return plan_err!(
"MATCH_RECOGNIZE aggregate '{}({}.*)' cannot contain multiple qualified wildcards",
name,
qualifier
);
}
wildcard_symbol = Some(symbol.to_owned());
} else {
return plan_err!(
"MATCH_RECOGNIZE aggregate 'COUNT({}.*)' must use a declared pattern symbol",
qualifier
);
}
}
_ => {
return plan_err!(
"MATCH_RECOGNIZE aggregate '{}' only supports positional expression arguments",
name
);
}
}
}
if wildcard_symbol.is_some() && !args.is_empty() {
return plan_err!(
"MATCH_RECOGNIZE aggregate '{}({}.*)' cannot mix wildcard and expression arguments",
name,
wildcard_symbol.as_deref().unwrap_or("")
);
}
let within_group = !func.within_group.is_empty();
let mut order_by = func.within_group;
let mut null_treatment = func.null_treatment;
for arg_clause in &arg_list.clauses {
match arg_clause {
FunctionArgumentClause::OrderBy(items) => {
if within_group {
return plan_err!(
"ORDER BY and WITHIN GROUP clauses cannot be used together in the same aggregate function"
);
}
order_by.extend(items.iter().cloned());
}
FunctionArgumentClause::IgnoreOrRespectNulls(treatment) => {
if null_treatment.is_some() {
return not_impl_err!(
"Calling {name}: Duplicated null treatment clause"
);
}
null_treatment = Some(*treatment);
}
_ => {
return plan_err!(
"MATCH_RECOGNIZE aggregate '{}' does not support argument clause '{}'",
name,
arg_clause
);
}
}
}
if null_treatment.is_some()
&& let Some(udaf) = self.context.get_aggregate_meta(&name)
&& !udaf.supports_null_handling_clause()
{
return plan_err!(
"[IGNORE | RESPECT] NULLS are not permitted for {}",
udaf.name()
);
}
let order_by = order_by
.into_iter()
.map(|sort| {
let asc = sort_ascending(&sort)?;
let expr = self.adapt_expr(clause, sort.expr)?.expr;
Ok(MatchExprSort {
expr: Box::new(expr),
asc,
nulls_first: sort.options.nulls_first.unwrap_or_else(|| {
NullOrdering::from(
self.context
.options()
.sql_parser
.default_null_ordering
.as_str(),
)
.nulls_first(asc)
}),
})
})
.collect::<Result<Vec<_>>>()?;
if !order_by.is_empty() {
let ordered_set = self
.context
.get_aggregate_meta(&name)
.is_some_and(|udaf| udaf.supports_within_group_clause());
if ordered_set {
let [sort] = order_by.as_slice() else {
return plan_err!(
"Only a single ordering expression is permitted in WITHIN GROUP clause"
);
};
if within_group {
args.insert(0, (*sort.expr).clone());
}
} else if within_group {
return plan_err!(
"WITHIN GROUP is only supported for ordered-set aggregate functions"
);
}
}
let filter = func
.filter
.map(|filter| self.adapt_expr(clause, *filter).map(|e| Box::new(e.expr)))
.transpose()?;
Ok(AdaptedSqlExpr {
expr: ParsedMatchExpr::Aggregate(MatchAggregateCall {
name,
args,
distinct,
filter,
order_by,
null_treatment: null_treatment.map(Into::into),
wildcard_symbol,
}),
structured: true,
})
}
pub(super) fn adapt_literal_or_expr(
&self,
clause: SqlClause,
expr: SQLExpr,
) -> Result<AdaptedSqlExpr> {
if let Some(literal) = sql_literal_source_expr(&expr)? {
return Ok(AdaptedSqlExpr {
expr: literal,
structured: false,
});
}
self.adapt_expr(clause, expr)
}
pub(super) fn inject_define_window(
&self,
clause: SqlClause,
mut func: Function,
) -> Result<Function> {
if !matches!(clause, SqlClause::Define) {
return Ok(func);
}
let spec = match func.over.take() {
None => WindowSpec {
window_name: None,
partition_by: self.partition_by.to_vec(),
order_by: self.order_by.to_vec(),
window_frame: Some(default_define_window_frame()),
},
Some(
WindowType::NamedWindow(name)
| WindowType::WindowSpec(WindowSpec {
window_name: Some(name),
..
}),
) => {
return plan_err!(
"MATCH_RECOGNIZE DEFINE does not support named window '{}'",
name
);
}
Some(WindowType::WindowSpec(mut spec)) => {
let (inject_partition, inject_order, inject_frame) =
self.define_window_defaults(&spec);
if inject_partition {
spec.partition_by = self.partition_by.to_vec();
}
if inject_order {
spec.order_by = self.order_by.to_vec();
}
if inject_frame {
spec.window_frame = Some(default_define_window_frame());
}
spec
}
};
func.over = Some(WindowType::WindowSpec(spec));
Ok(func)
}
fn define_window_defaults(&self, spec: &WindowSpec) -> (bool, bool, bool) {
let missing_order = spec.order_by.is_empty();
(
spec.partition_by.is_empty() && !self.partition_by.is_empty(),
missing_order && !self.order_by.is_empty(),
missing_order && spec.window_frame.is_none(),
)
}
fn pattern_symbol(&self, name: &str) -> Option<&str> {
self.pattern_symbols
.iter()
.find(|symbol| symbol.eq_ignore_ascii_case(name))
.map(String::as_str)
}
}
fn expression_form(expr: &SQLExpr) -> &'static str {
match expr {
SQLExpr::Cast {
kind: CastKind::TryCast,
..
} => "TRY_CAST",
SQLExpr::Cast {
kind: CastKind::SafeCast,
..
} => "SAFE_CAST",
SQLExpr::Tuple(..) => "tuple",
SQLExpr::Extract { .. } => "EXTRACT",
SQLExpr::Position { .. } => "POSITION",
SQLExpr::Trim { .. } => "TRIM",
SQLExpr::Overlay { .. } => "OVERLAY",
SQLExpr::AtTimeZone { .. } => "AT TIME ZONE",
SQLExpr::Collate { .. } => "COLLATE",
SQLExpr::Interval(..) => "INTERVAL",
SQLExpr::CompoundFieldAccess { .. } => "field access",
SQLExpr::AnyOp { .. } | SQLExpr::AllOp { .. } => "quantified comparison",
_ => "this expression form",
}
}
fn is_nested_simple_leaf(expr: &SQLExpr) -> bool {
let SQLExpr::Nested(inner) = expr else {
return false;
};
let mut inner = inner.as_ref();
while let SQLExpr::Nested(next) = inner {
inner = next.as_ref();
}
matches!(
inner,
SQLExpr::Identifier(_) | SQLExpr::CompoundIdentifier(_) | SQLExpr::Value(_)
)
}
pub(super) fn dismantle_sql_expr(expr: SQLExpr) {
let mut stack = match expr {
SQLExpr::BinaryOp { left, right, .. } => vec![*left, *right],
SQLExpr::Nested(inner) | SQLExpr::UnaryOp { expr: inner, .. } => vec![*inner],
_ => return,
};
while let Some(node) = stack.pop() {
match node {
SQLExpr::BinaryOp { left, right, .. } => {
stack.push(*left);
stack.push(*right);
}
SQLExpr::Nested(inner) | SQLExpr::UnaryOp { expr: inner, .. } => {
stack.push(*inner);
}
_ => {}
}
}
}
pub(super) fn dismantle_parsed_match_expr(expr: ParsedMatchExpr) {
let mut stack = vec![expr];
while let Some(node) = stack.pop() {
match node {
ParsedMatchExpr::Binary { left, right, .. } => {
stack.push(*left);
stack.push(*right);
}
ParsedMatchExpr::InputExpr(sql) => dismantle_sql_expr(*sql),
ParsedMatchExpr::Unary { expr, .. }
| ParsedMatchExpr::Predicate { expr, .. }
| ParsedMatchExpr::Cast { expr, .. }
| ParsedMatchExpr::Alias { expr, .. } => stack.push(*expr),
_ => {}
}
}
}
impl AdaptedSqlExpr {
pub(super) fn input(expr: SQLExpr) -> Self {
Self {
expr: parsed_input(expr),
structured: false,
}
}
}