use std::cell::RefCell;
use super::syntax::strip_outer_parentheses;
use super::*;
pub(super) fn plan_bound_match(
context: &mut dyn RelationPlannerContext,
input: LogicalPlan,
bound_spec: BoundMatchSpec,
) -> Result<LogicalPlan> {
let mut planning_context = SqlPlanningContext {
provider: context.context_provider(),
};
plan_match_recognize_from_source(&mut planning_context, input, bound_spec)
}
pub(super) fn bind_parsed_match_clause(
context: &mut dyn RelationPlannerContext,
schema: &DFSchema,
spec: ParsedMatchClause,
) -> Result<BoundMatchSpec> {
Ok(BoundMatchSpec {
partition_by: spec
.partition_by
.into_iter()
.map(|expr| bind_parsed_match_expr(context, schema, expr))
.collect::<Result<Vec<_>>>()?,
order_by: spec
.order_by
.into_iter()
.map(|sort| {
Ok(MatchRecognizeSortExpr {
expr: bind_parsed_match_expr(context, schema, sort.expr)?,
direction: sort.direction,
null_ordering: sort.null_ordering,
})
})
.collect::<Result<Vec<_>>>()?,
source_rows_per_match: spec.source_rows_per_match,
after_match_skip: spec.after_match_skip,
pattern: spec.pattern,
symbols: spec.symbols,
definitions: spec
.definitions
.into_iter()
.map(|definition| {
Ok(MatchRecognizeDefinition {
symbol: definition.symbol,
predicate: bind_parsed_match_expr(
context,
schema,
definition.predicate,
)?,
})
})
.collect::<Result<Vec<_>>>()?,
measures: spec
.measures
.into_iter()
.map(|measure| {
Ok(MatchRecognizeMeasure {
name: measure.name,
expression: bind_parsed_match_expr(
context,
schema,
measure.expression,
)?,
})
})
.collect::<Result<Vec<_>>>()?,
output: match spec.output {
MatchRecognizeOutputContract::Derived => {
MatchRecognizeOutputContract::Derived
}
MatchRecognizeOutputContract::ExplicitNamedExpressions(expressions) => {
MatchRecognizeOutputContract::ExplicitNamedExpressions(
expressions
.into_iter()
.map(|expression| {
Ok(MatchRecognizeNamedExpression {
name: expression.name,
expression: bind_parsed_match_expr(
context,
schema,
expression.expression,
)?,
})
})
.collect::<Result<Vec<_>>>()?,
)
}
},
})
}
pub(super) fn bind_parsed_match_expr(
context: &mut dyn RelationPlannerContext,
schema: &DFSchema,
expr: ParsedMatchExpr,
) -> Result<BoundMatchExpr> {
let context = RefCell::new(context);
let mut bound = expr.try_map_adapter_parts(
&mut |expr| {
context
.borrow_mut()
.sql_to_expr(strip_outer_parentheses(*expr), schema)
},
&mut |column| Ok(Column::from_name(column)),
&mut |field| {
Ok(MatchPatternFieldRef {
symbol: field.symbol,
column: Column::from_name(context.borrow().normalize_ident(field.column)),
})
},
&mut |data_type| cast_target(&mut **context.borrow_mut(), schema, data_type),
)?;
supply_ordered_set_values(context.borrow().context_provider(), &mut bound);
Ok(bound)
}
fn supply_ordered_set_values(context: &dyn ContextProvider, expr: &mut BoundMatchExpr) {
let mut pending = vec![expr];
while let Some(expr) = pending.pop() {
match expr {
BoundMatchExpr::Aggregate(call) => {
if let [sort] = call.order_by.as_slice()
&& context
.get_aggregate_meta(&call.name)
.is_some_and(|udaf| udaf.supports_within_group_clause())
&& call.args.first() != Some(sort.expr.as_ref())
{
call.args.insert(0, (*sort.expr).clone());
}
pending.extend(&mut call.args);
pending.extend(call.filter.as_deref_mut());
pending.extend(call.order_by.iter_mut().map(|sort| sort.expr.as_mut()));
}
BoundMatchExpr::Navigation(nav) => match nav {
MatchNavigation::First { expr, offset }
| MatchNavigation::Last { expr, offset } => {
pending.push(expr);
pending.extend(offset.as_deref_mut());
}
MatchNavigation::Prev {
expr,
offset,
default,
}
| MatchNavigation::Next {
expr,
offset,
default,
} => {
pending.push(expr);
pending.extend(offset.as_deref_mut());
pending.extend(default.as_deref_mut());
}
},
BoundMatchExpr::Alias { expr, .. }
| BoundMatchExpr::Unary { expr, .. }
| BoundMatchExpr::Predicate { expr, .. }
| BoundMatchExpr::Cast { expr, .. } => pending.push(expr),
BoundMatchExpr::ScalarFunction { args, .. } => pending.extend(args),
BoundMatchExpr::Binary { left, right, .. }
| BoundMatchExpr::Like {
expr: left,
pattern: right,
..
} => {
pending.push(right);
pending.push(left);
}
BoundMatchExpr::Case {
expr,
when_then,
else_expr,
} => {
pending.extend(expr.as_deref_mut());
for (when, then) in when_then {
pending.push(when);
pending.push(then);
}
pending.extend(else_expr.as_deref_mut());
}
BoundMatchExpr::Between {
expr, low, high, ..
} => {
pending.push(expr);
pending.push(low);
pending.push(high);
}
BoundMatchExpr::InList { expr, list, .. } => {
pending.push(expr);
pending.extend(list);
}
BoundMatchExpr::InputExpr(_)
| BoundMatchExpr::InputColumn(_)
| BoundMatchExpr::PatternField(_)
| BoundMatchExpr::Metadata(_)
| BoundMatchExpr::Literal(_) => {}
}
}
}
fn cast_target(
context: &mut dyn RelationPlannerContext,
schema: &DFSchema,
data_type: SQLDataType,
) -> Result<ArrowDataType> {
let expr = context.sql_to_expr(
SQLExpr::Cast {
kind: CastKind::Cast,
expr: Box::new(SQLExpr::Value(Value::Null.into())),
data_type,
format: None,
},
schema,
)?;
match expr {
datafusion::logical_expr::Expr::Cast(cast) => {
if !cast.field.name().is_empty()
|| !cast.field.is_nullable()
|| !cast.field.metadata().is_empty()
{
return plan_err!(
"MATCH_RECOGNIZE CAST does not support explicit target fields"
);
}
Ok(cast.field.data_type().clone())
}
_ => internal_err!("DataFusion did not return CAST for a cast target probe"),
}
}
struct SqlPlanningContext<'a> {
provider: &'a dyn ContextProvider,
}
impl MatchRecognizePlanningContext for SqlPlanningContext<'_> {
fn options(&self) -> &ConfigOptions {
self.provider.options()
}
fn scalar_udf(&self, name: &str) -> Option<Arc<ScalarUDF>> {
self.provider.get_function_meta(name)
}
fn aggregate_udf(&self, name: &str) -> Option<Arc<AggregateUDF>> {
self.provider
.get_aggregate_meta(name)
.or_else(|| self.options().aggregate_udf(name))
}
}