use std::sync::Arc;
use datafusion::common::tree_node::{Transformed, TreeNodeRecursion};
use datafusion::common::{DataFusionError, Result, SchemaError};
use datafusion::execution::SessionStateBuilder;
use datafusion::logical_expr::{Expr, LogicalPlan};
use datafusion::optimizer::{ApplyOrder, OptimizerConfig, OptimizerRule};
use crate::planning::logical::MatchRecognize;
#[derive(Debug)]
struct Branch55LeafProjectionGuard {
inner: Arc<dyn OptimizerRule + Send + Sync>,
}
impl Branch55LeafProjectionGuard {
fn new(inner: Arc<dyn OptimizerRule + Send + Sync>) -> Self {
Self { inner }
}
}
fn has_qualifier_stripping_alias(exprs: &[Expr]) -> bool {
exprs.iter().any(|expr| {
matches!(
expr,
Expr::Alias(alias)
if alias.relation.is_none()
&& matches!(
alias.expr.as_ref(),
Expr::Column(col)
if col.relation.is_some() && col.name == alias.name
)
)
})
}
fn contains_match_recognize_with_qualifier_strip(plan: &LogicalPlan) -> bool {
let mut has_match_recognize = false;
let mut has_qualifier_strip = false;
let _ = plan.apply_with_subqueries(|node| {
match node {
LogicalPlan::Extension(ext) if ext.node.as_any().is::<MatchRecognize>() => {
has_match_recognize = true;
}
LogicalPlan::Projection(proj)
if !has_qualifier_strip && has_qualifier_stripping_alias(&proj.expr) =>
{
has_qualifier_strip = true;
}
_ => {}
}
Ok(if has_match_recognize && has_qualifier_strip {
TreeNodeRecursion::Stop
} else {
TreeNodeRecursion::Continue
})
});
has_match_recognize && has_qualifier_strip
}
fn is_ambiguous_reference(err: &DataFusionError) -> bool {
matches!(
err.find_root(),
DataFusionError::SchemaError(schema_err, _)
if matches!(schema_err.as_ref(), SchemaError::AmbiguousReference { .. })
)
}
impl OptimizerRule for Branch55LeafProjectionGuard {
fn name(&self) -> &str {
self.inner.name()
}
fn apply_order(&self) -> Option<ApplyOrder> {
self.inner.apply_order()
}
fn rewrite(
&self,
plan: LogicalPlan,
config: &dyn OptimizerConfig,
) -> Result<Transformed<LogicalPlan>> {
if !contains_match_recognize_with_qualifier_strip(&plan) {
return self.inner.rewrite(plan, config);
}
let original = plan.clone();
match self.inner.rewrite(plan, config) {
Ok(transformed) => Ok(transformed),
Err(err) if is_ambiguous_reference(&err) => Ok(Transformed::no(original)),
Err(err) => Err(err),
}
}
}
pub(crate) fn install_leaf_projection_workaround(
mut builder: SessionStateBuilder,
) -> SessionStateBuilder {
let mut optimizer = builder.optimizer().take().unwrap_or_default();
for rule in &mut optimizer.rules {
if matches!(
rule.name(),
"extract_leaf_expressions" | "push_down_leaf_projections"
) {
*rule = Arc::new(Branch55LeafProjectionGuard::new(Arc::clone(rule)));
}
}
builder.with_optimizer_rules(optimizer.rules)
}
#[cfg(all(test, feature = "sql"))]
mod tests {
use datafusion::arrow::array::Int64Array;
use datafusion::common::Result;
use datafusion::execution::SessionStateBuilder;
use crate::new_match_recognize_context;
#[tokio::test]
async fn leaf_expression_over_qualifier_stripped_match_recognize_executes()
-> Result<()> {
let ctx = new_match_recognize_context(
SessionStateBuilder::new().with_default_features(),
)?;
let base_cte = "WITH order_events AS (
SELECT 1 AS customer, 1 AS ord, 10 AS amount
UNION ALL SELECT 1, 2, 15
UNION ALL SELECT 2, 1, 20
), events AS (
SELECT *, named_struct('ord', ord) AS details
FROM order_events
)";
for sql in [
format!(
"{base_cte}
SELECT customer, first_details['ord'] AS d
FROM events MATCH_RECOGNIZE (
PARTITION BY customer ORDER BY ord
MEASURES FIRST(A.details) AS first_details
ONE ROW PER MATCH
PATTERN (A+) DEFINE A AS amount > 0
) ORDER BY customer"
),
format!(
"{base_cte}
SELECT customer, details['ord'] AS d
FROM events MATCH_RECOGNIZE (
PARTITION BY customer ORDER BY ord
ALL ROWS PER MATCH
PATTERN (A+) DEFINE A AS amount > 0
) WHERE ord = 1 ORDER BY customer"
),
format!(
"{base_cte}
SELECT mr.customer, mr.first_details['ord'] AS d
FROM (
SELECT * FROM events MATCH_RECOGNIZE (
PARTITION BY customer ORDER BY ord
MEASURES FIRST(A.details) AS first_details
ONE ROW PER MATCH
PATTERN (A+) DEFINE A AS amount > 0
)
) AS mr
WHERE mr.customer >= 1 AND mr.first_details['ord'] = 1
ORDER BY mr.customer"
),
] {
let batches = ctx.sql(&sql).await?.collect().await?;
let pairs: Vec<(i64, i64)> = batches
.iter()
.flat_map(|b| {
let c = b
.column(0)
.as_any()
.downcast_ref::<Int64Array>()
.expect("customer int64");
let d = b
.column(1)
.as_any()
.downcast_ref::<Int64Array>()
.expect("detail ord int64");
(0..b.num_rows()).map(|i| (c.value(i), d.value(i)))
})
.collect();
assert_eq!(pairs, vec![(1, 1), (2, 1)], "query failed:\n{sql}");
}
Ok(())
}
}