use super::*;
#[tokio::test]
async fn mixed_aggregates_roundtrip_ordinary_and_legacy_one_row_boundaries() -> Result<()>
{
let ctx = context_with_input().await?;
let sql = r#"
SELECT company, row_count, total_price
FROM t
MATCH_RECOGNIZE (
PARTITION BY company
ORDER BY ts
MEASURES
COUNT(*) AS row_count,
SUM(A.price) AS total_price
ONE ROW PER MATCH
AFTER MATCH SKIP PAST LAST ROW
PATTERN (A+)
DEFINE A AS price > 0
)
ORDER BY company, row_count, total_price
"#;
let direct = ctx.sql(sql).await?.logical_plan().clone();
let ordinary = ctx
.sql(&sql.replace("SUM(A.price)", "SUM(DISTINCT A.price)"))
.await?
.logical_plan()
.clone();
for (plan, native) in [(&direct, true), (&ordinary, false)] {
let exported = to_substrait_plan_with_match_recognize(plan, &ctx.state())?;
let payload = root_payload(&exported)?;
assert!(payload.semantic_node);
assert_eq!(payload.semantic_node_finalizes_one_row, native);
assert_roundtrip_output(
&ctx,
plan.clone(),
&[
("company", DataType::Utf8, true),
("row_count", DataType::Int64, false),
("total_price", DataType::Int64, true),
],
&[vec!["acme".into(), 3_i64.into(), 36_i64.into()]],
)
.await?;
}
let source = match_recognize_node(&ordinary)
.unwrap()
.bound_source()
.unwrap();
let legacy = plan_match_recognize_native_one_row_node_from_source_with_capabilities(
&mut crate::planning::DefaultMatchRecognizePlanningContext::new(),
source.input().clone(),
source.canonical_spec().as_spec().clone(),
source.capabilities(),
)?;
let legacy = LogicalPlanBuilder::from(legacy)
.project(vec![
col("price").alias("representative_price"),
col("__mr_count_summary_0").alias("row_count"),
col("__mr_count_summary_1").alias("total_price"),
])?
.build()?;
let legacy_export = to_substrait_plan_with_match_recognize(&legacy, &ctx.state())?;
assert!(root_payload(&legacy_export)?.semantic_node_finalizes_one_row);
assert_roundtrip_output(
&ctx,
legacy,
&[
("representative_price", DataType::Int64, true),
("row_count", DataType::Int64, false),
("total_price", DataType::Int64, true),
],
&[vec![10_i64.into(), 3_i64.into(), 36_i64.into()]],
)
.await
}
#[tokio::test]
async fn pruned_native_one_row_node_roundtrips_without_summary_columns() -> Result<()> {
let ctx = context_with_input().await?;
let direct = sql_plan(
&ctx,
"SELECT company, row_count FROM t MATCH_RECOGNIZE (
PARTITION BY company ORDER BY ts MEASURES COUNT(*) AS row_count
ONE ROW PER MATCH PATTERN (A+) DEFINE A AS price>0)",
)
.await?;
let node = match_recognize_node(&direct).expect("native logical node");
let output = node
.pruned_output_for_projection_exprs(&[col("company")])
.expect("summary output should be pruned");
let pruned = node.rebuild_with_output(output)?;
assert!(pruned.program().selected_match_summaries().is_empty());
let pruned = LogicalPlan::Extension(Extension {
node: Arc::new(pruned),
});
let exported = to_substrait_plan_with_match_recognize(&pruned, &ctx.state())?;
assert!(root_payload(&exported)?.semantic_node_finalizes_one_row);
assert_roundtrip_output(
&ctx,
pruned,
&[("company", DataType::Utf8, true)],
&[vec!["acme".into()]],
)
.await
}
#[tokio::test]
async fn optimized_exports_preserve_rows() -> Result<()> {
let ctx = export_context().await?;
for (case, sql, columns, rows) in [
(
"partition filter",
"SELECT k, n FROM export_input MATCH_RECOGNIZE (
PARTITION BY k ORDER BY ts MEASURES COUNT(*) AS n
PATTERN (A+) DEFINE A AS true) WHERE k = 1 ORDER BY k",
vec![("k", DataType::Int64, true), ("n", DataType::Int64, false)],
vec![vec![1_i64.into(), 3_i64.into()]],
),
(
"pruned DEFINE input",
"SELECT k, n FROM export_input MATCH_RECOGNIZE (
PARTITION BY k ORDER BY ts MEASURES COUNT(*) AS n
PATTERN (A+) DEFINE A AS price > 12) ORDER BY k",
vec![("k", DataType::Int64, true), ("n", DataType::Int64, false)],
vec![vec![1_i64.into(), 2_i64.into()]],
),
(
"swapped passthrough",
"WITH input AS (
SELECT ts, a AS b, b AS a FROM alias_input)
SELECT a, n FROM input MATCH_RECOGNIZE (
PARTITION BY a ORDER BY ts MEASURES COUNT(*) AS n
PATTERN (A+) DEFINE A AS true) ORDER BY a",
vec![("a", DataType::Int64, true), ("n", DataType::Int64, false)],
vec![
vec![10_i64.into(), 1_i64.into()],
vec![20_i64.into(), 2_i64.into()],
],
),
(
"retained second summary without source output",
"SELECT total FROM export_input MATCH_RECOGNIZE (
ORDER BY ts MEASURES COUNT(*) AS unused, SUM(A.price) AS total
ONE ROW PER MATCH PATTERN (A+) DEFINE A AS true)",
vec![("total", DataType::Int64, true)],
vec![vec![63_i64.into()]],
),
] {
let direct = sql_plan(&ctx, sql).await?;
let optimized = ctx.state().optimize(&direct)?;
if case == "pruned DEFINE input" {
let node = match_recognize_node(&optimized).expect("optimized match node");
assert!(
node.input()
.schema()
.index_of_column(&Column::new(Some("export_input"), "price"))
.is_err()
);
} else if case == "retained second summary without source output" {
let node = match_recognize_node(&optimized).expect("optimized match node");
let output = node.program().output();
assert!(output.spec().passthrough_input_indices().is_empty());
let summaries = output.selected_match_summaries();
assert_eq!(summaries.len(), 1);
assert_eq!(summaries[0].output_id(), 1);
}
assert_roundtrip_output(&ctx, optimized, &columns, &rows).await?;
}
let baseline = sql_plan(&ctx, "SELECT k, n FROM export_input MATCH_RECOGNIZE (
PARTITION BY k ORDER BY ts MEASURES COUNT(*) AS n PATTERN (A+) DEFINE A AS true) ORDER BY k").await?;
let columns = [("k", DataType::Int64, true), ("n", DataType::Int64, false)];
assert_output(
&ctx,
baseline.clone(),
&columns,
&[
vec![1_i64.into(), 3_i64.into()],
vec![2_i64.into(), 3_i64.into()],
],
)
.await?;
let rewritten = baseline
.transform_up(|plan| {
if matches!(plan, LogicalPlan::TableScan(_)) {
Ok(Transformed::yes(
LogicalPlanBuilder::from(plan)
.filter(col("export_input.k").eq(lit(2_i64)))?
.build()?,
))
} else {
Ok(Transformed::no(plan))
}
})?
.data;
assert_roundtrip_output(
&ctx,
rewritten,
&columns,
&[vec![2_i64.into(), 3_i64.into()]],
)
.await?;
Ok(())
}
#[tokio::test]
async fn reordered_row_output_preserves_explicit_identity() -> Result<()> {
let ctx = export_context().await?;
let plan = sql_plan(
&ctx,
"SELECT * FROM export_input MATCH_RECOGNIZE (
ORDER BY ts, k MEASURES MATCH_NUMBER() AS mn
ALL ROWS PER MATCH PATTERN (A B) DEFINE A AS true, B AS true)",
)
.await?;
let node = match_recognize_node(&plan).expect("row-stream node");
let output = node.program().output();
let spec = output.spec();
for group in 0..3 {
let mut passthrough = spec.passthrough_input_indices().to_vec();
let mut metadata = spec.metadata_columns().to_vec();
let mut classifiers = spec.classifier_bitset_symbols().to_vec();
match group {
0 => passthrough.swap(0, 1),
1 => metadata.swap(0, 1),
_ => classifiers.swap(0, 1),
}
let reordered = node.rebuild_with_output(LogicalMatchOutput::rows(
output.rows_per_match().clone(),
MatchRecognizeOutputSpec::with_validated_navigation_offsets(
passthrough,
metadata,
classifiers,
spec.navigation_offsets(),
),
))?;
let reordered = LogicalPlan::Extension(Extension {
node: Arc::new(reordered),
});
let expected = plan_rows(&ctx, reordered.clone()).await?;
assert_eq!(
roundtrip_rows(&ctx, &reordered).await?,
expected,
"group {group}"
);
}
Ok(())
}
#[tokio::test]
async fn optimized_navigation_export_is_safe() -> Result<()> {
let ctx = export_context().await?;
let direct = sql_plan(&ctx, "SELECT k, ts, previous, running FROM export_input MATCH_RECOGNIZE (
PARTITION BY k ORDER BY ts MEASURES PREV(price) AS previous, SUM(A.price) AS running
ALL ROWS PER MATCH PATTERN (A+) DEFINE A AS true) ORDER BY k, ts").await?;
let optimized = ctx.state().optimize(&direct)?;
assert_roundtrip_output(
&ctx,
optimized,
&[
("k", DataType::Int64, true),
("ts", DataType::Int64, true),
("previous", DataType::Int64, true),
("running", DataType::Int64, true),
],
&[
vec![
1_i64.into(),
1_i64.into(),
datafusion::common::ScalarValue::Int64(None),
10_i64.into(),
],
vec![1_i64.into(), 2_i64.into(), 10_i64.into(), 30_i64.into()],
vec![1_i64.into(), 3_i64.into(), 20_i64.into(), 45_i64.into()],
vec![
2_i64.into(),
1_i64.into(),
datafusion::common::ScalarValue::Int64(None),
5_i64.into(),
],
vec![2_i64.into(), 2_i64.into(), 5_i64.into(), 11_i64.into()],
vec![2_i64.into(), 3_i64.into(), 6_i64.into(), 18_i64.into()],
],
)
.await
}
#[tokio::test]
async fn changed_input_export_is_safe() -> Result<()> {
let ctx = export_context().await?;
let direct = sql_plan(
&ctx,
"SELECT k, n, total FROM export_input MATCH_RECOGNIZE (
PARTITION BY k ORDER BY ts MEASURES COUNT(*) AS n, SUM(A.price) AS total
PATTERN (A+) DEFINE A AS price > 12) ORDER BY k",
)
.await?;
let changed = rewrite_match_input(direct.clone(), |input| {
project_input_column(input, "price", col("export_input.price") + lit(100_i64))
})?;
let columns = [
("k", DataType::Int64, true),
("n", DataType::Int64, false),
("total", DataType::Int64, true),
];
assert_output(
&ctx,
direct,
&columns,
&[vec![1_i64.into(), 2_i64.into(), 35_i64.into()]],
)
.await?;
assert_output(
&ctx,
changed.clone(),
&columns,
&[vec![1_i64.into(), 2_i64.into(), 235_i64.into()]],
)
.await?;
assert_export_rejected(
&ctx,
&changed,
"rewritten input boundary containing prepared column '__mr_symbol_a'",
);
Ok(())
}
#[tokio::test]
async fn changed_static_masks_do_not_recompute_original_define() -> Result<()> {
let ctx = export_context().await?;
let direct = sql_plan(
&ctx,
"SELECT k, n FROM export_input MATCH_RECOGNIZE (
PARTITION BY k ORDER BY ts MEASURES COUNT(*) AS n
PATTERN (A+) DEFINE A AS price > 12) ORDER BY k",
)
.await?;
let columns = [("k", DataType::Int64, true), ("n", DataType::Int64, false)];
assert_output(
&ctx,
direct.clone(),
&columns,
&[vec![1_i64.into(), 2_i64.into()]],
)
.await?;
let projected = rewrite_match_input(direct.clone(), |input| {
project_input_column(input, "__mr_symbol_a", lit(true))
})?;
let merged =
rewrite_prepared_projection(direct.clone(), "__mr_symbol_a", |_| Ok(lit(true)))?;
let window = rewrite_match_input(direct, |input| {
let windowed =
replace_column_with_lag(input, "__mr_symbol_a", lit(true), lit(true))?;
LogicalPlanBuilder::from(windowed)
.project(input.schema().columns().into_iter().map(|column| {
if column.name == "__mr_symbol_a" {
Expr::IsTrue(Box::new(Expr::Column(column))).alias("__mr_symbol_a")
} else {
Expr::Column(column)
}
}))?
.build()
})?;
for (changed, optimize, rejection) in [
(projected, false, "rewritten prepared column"),
(merged, true, "No field named export_input.price"),
(window, false, "rewritten prepared column"),
] {
let changed = if optimize {
ctx.state().optimize(&changed)?
} else {
changed
};
assert_output(
&ctx,
changed.clone(),
&columns,
&[
vec![1_i64.into(), 3_i64.into()],
vec![2_i64.into(), 3_i64.into()],
],
)
.await?;
assert_export_rejected(&ctx, &changed, rejection);
}
Ok(())
}
#[tokio::test]
async fn prepared_navigation_boundaries_are_safe() -> Result<()> {
let ctx = context_with_input().await?;
for (predicate, fetch) in [
("price > PREV(price)", None),
("price < NEXT(price)", Some(2)),
] {
let direct = sql_plan(
&ctx,
&format!(
"SELECT n FROM t MATCH_RECOGNIZE (
ORDER BY ts MEASURES COUNT(*) AS n
PATTERN (A+) DEFINE A AS {predicate})"
),
)
.await?;
let changed = rewrite_match_input(direct, |input| {
let input = LogicalPlanBuilder::from(input.clone());
if let Some(fetch) = fetch {
input.limit(0, Some(fetch))?
} else {
input.filter(col("t.ts").gt(lit(1_i64)))?
}
.build()
})?;
assert_output(
&ctx,
changed.clone(),
&[("n", DataType::Int64, false)],
&[vec![2_i64.into()]],
)
.await?;
assert_export_rejected(
&ctx,
&changed,
"rewritten input boundary containing prepared column '__mr_expr_0'",
);
}
Ok(())
}
#[tokio::test]
async fn all_rows_filtered_aggregate_windows_roundtrip_execution() -> Result<()> {
let ctx = context_with_input().await?;
let queries = [
r#"
SELECT company, ts, cls, b_count, b_sum
FROM t
MATCH_RECOGNIZE (
PARTITION BY company
ORDER BY ts
MEASURES
CLASSIFIER() AS cls,
COUNT(B.*) AS b_count,
SUM(B.price) AS b_sum
ALL ROWS PER MATCH
AFTER MATCH SKIP PAST LAST ROW
PATTERN (A B*)
DEFINE
A AS price = 10,
B AS price > 10
)
ORDER BY company, ts
"#,
r#"
SELECT company, ts, row_count
FROM t
MATCH_RECOGNIZE (
PARTITION BY company
ORDER BY ts
MEASURES COUNT(*) AS row_count
ALL ROWS PER MATCH SHOW EMPTY MATCHES
AFTER MATCH SKIP TO NEXT ROW
PATTERN (A*)
DEFINE A AS price < 0
)
ORDER BY company, ts
"#,
];
let cases = [
(
vec![
("company", DataType::Utf8, true),
("ts", DataType::Int64, true),
("cls", DataType::Utf8, true),
("b_count", DataType::Int64, false),
("b_sum", DataType::Int64, true),
],
vec![
vec![
"acme".into(),
1_i64.into(),
"A".into(),
0_i64.into(),
datafusion::common::ScalarValue::Int64(None),
],
vec![
"acme".into(),
2_i64.into(),
"B".into(),
1_i64.into(),
12_i64.into(),
],
vec![
"acme".into(),
3_i64.into(),
"B".into(),
2_i64.into(),
26_i64.into(),
],
],
),
(
vec![
("company", DataType::Utf8, true),
("ts", DataType::Int64, true),
("row_count", DataType::Int64, false),
],
vec![
vec!["acme".into(), 1_i64.into(), 0_i64.into()],
vec!["acme".into(), 2_i64.into(), 0_i64.into()],
vec!["acme".into(), 3_i64.into(), 0_i64.into()],
],
),
];
assert_eq!(
queries.len(),
cases.len(),
"every SQL case needs a literal oracle"
);
for (sql, (columns, rows)) in queries.into_iter().zip(cases) {
assert_roundtrip_output(&ctx, sql_plan(&ctx, sql).await?, &columns, &rows)
.await?;
}
Ok(())
}
#[tokio::test]
async fn export_required_features_follow_actual_metadata_usage() -> Result<()> {
let ctx = context_with_input().await?;
for (function, required) in [
(None, None),
(
Some(payload::MetadataFunction::MatchSequenceNumber),
Some(DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE),
),
(
Some(payload::MetadataFunction::Excluded),
Some(DATAFUSION_EXCLUDED_FEATURE),
),
] {
let mut source = base_payload();
source.required_features.extend([
DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE.into(),
DATAFUSION_EXCLUDED_FEATURE.into(),
]);
if let Some(function) = function {
source.measures.push(payload::RowPatternMeasure {
name: Some("extra".into()),
expression: Some(metadata(function)),
});
let ty = if function == payload::MetadataFunction::Excluded {
bool_type()
} else {
i64_type()
};
source.output_schema = Some(named_struct(vec![
("company", string_type()),
("last_price", i64_type()),
("extra", ty),
]));
}
let imported = from_substrait_plan_with_match_recognize(
&ctx.state(),
&plan_for_payload(source),
)
.await?;
let exported = to_substrait_plan_with_match_recognize(&imported, &ctx.state())?;
let actual = root_payload(&exported)?
.required_features
.into_iter()
.filter(|name| {
matches!(
name.as_str(),
DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE
| DATAFUSION_EXCLUDED_FEATURE
)
})
.collect::<BTreeSet<_>>();
assert_eq!(actual, required.into_iter().map(str::to_owned).collect());
}
Ok(())
}
#[tokio::test]
async fn export_payload_keeps_source_expressions_adapter_level() -> Result<()> {
use payload::source_expression::Kind;
let ctx = context_with_input().await?;
let input = base_payload();
let imported = from_substrait_plan_with_match_recognize(
&ctx.state(),
&plan_for_payload(input.clone()),
)
.await?;
let exported = to_substrait_plan_with_match_recognize(&imported, &ctx.state())?;
let payload = root_payload(&exported)?;
let expr = |kind| payload::SourceExpression { kind: Some(kind) };
let literal = |value| {
expr(Kind::InputExpression(Expression {
rex_type: Some(RexType::Literal(proto::expression::Literal {
literal_type: Some(proto::expression::literal::LiteralType::I64(value)),
nullable: false,
type_variation_reference: 0,
})),
}))
};
let greater = |left, right| {
expr(Kind::Binary(payload::BinaryExpr {
left: Some(Box::new(left)),
op: payload::BinaryOperator::Gt as i32,
right: Some(Box::new(right)),
}))
};
assert_eq!(payload.symbols, input.symbols);
assert_eq!(payload.pattern, input.pattern);
assert_eq!(payload.partition_expressions, input.partition_expressions);
assert_eq!(payload.sorts, input.sorts);
assert_eq!(payload.measures, input.measures);
assert_eq!(
payload.definitions,
[
payload::PatternDefinition {
symbol: "A".into(),
predicate: Some(greater(input_field(2), literal(0)))
},
payload::PatternDefinition {
symbol: "B".into(),
predicate: Some(greater(pattern_field("B", 2), literal(10)))
},
]
);
Ok(())
}
#[tokio::test]
async fn extension_graph_exports_zero_root_parent_and_independent_children() -> Result<()>
{
let ctx = context_with_input().await?;
let root = from_substrait_plan_with_match_recognize(
&ctx.state(),
&plan_for_payload(base_payload()),
)
.await?;
let right = from_substrait_plan_with_match_recognize(
&ctx.state(),
&plan_for_payload(base_payload()),
)
.await?;
let matcher = LogicalPlan::Extension(Extension {
node: Arc::new(match_recognize_node(&root).expect("matcher").clone()),
});
let cases = [
(LogicalPlanBuilder::empty(false).build()?, "read", 0),
(matcher, "matcher", 1),
(
LogicalPlanBuilder::from(root.clone())
.project(vec![col("company")])?
.build()?,
"projection",
1,
),
(
LogicalPlanBuilder::from(root).union(right)?.build()?,
"union",
2,
),
];
for (plan, expected_root, count) in cases {
let exported = to_substrait_plan_with_match_recognize(&plan, &ctx.state())?;
let expected_urls = if count == 0 {
vec![]
} else {
vec![MATCH_RECOGNIZE_TYPE_URL.to_owned()]
};
assert_eq!(exported.expected_type_urls, expected_urls);
let root = root_rel(&exported);
let kind = match root.rel_type.as_ref().unwrap() {
RelType::Read(_) => "read",
RelType::ExtensionSingle(_) => "matcher",
RelType::Project(_) => "projection",
RelType::Set(_) => "union",
other => panic!("unexpected exported graph root: {other:?}"),
};
assert_eq!(kind, expected_root);
let mut details = vec![];
collect_match_recognize_details(root, &mut details);
assert_eq!(details.len(), count);
}
Ok(())
}
#[tokio::test]
async fn programmatic_summary_preserves_raw_float_partition_identity() -> Result<()> {
use crate::core::{MatchSummaryField, RepetitionQuantifier, symbol_col_name};
use crate::planning::logical::LogicalSelectedMatchSummary;
use datafusion::arrow::array::{BooleanArray, Float64Array};
use datafusion::logical_expr::ExprSchemable;
let ctx = context_with_input().await?;
let values = [0_u64, 1 << 63, f64::NAN.to_bits(), f64::NAN.to_bits() + 1];
ctx.register_batch(
"raw_keys",
RecordBatch::try_from_iter(vec![
(
"k",
Arc::new(Float64Array::from_iter_values(values.map(f64::from_bits)))
as ArrayRef,
),
("v", Arc::new(Int64Array::from(vec![1; 4])) as ArrayRef),
(
&symbol_col_name("A"),
Arc::new(BooleanArray::from(vec![true; 4])) as ArrayRef,
),
])?,
)?;
let input = ctx.table("raw_keys").await?.logical_plan().clone();
let private = MatchRecognizeOutputSpec::new(vec![1], vec![], vec![]);
let count = datafusion::functions_aggregate::count::count(col("v"));
let (_, field) = count.to_field(private.build_df_schema(input.schema())?.as_ref())?;
let Expr::AggregateFunction(count) = count else {
unreachable!()
};
let node = MatchRecognize::try_new(
input,
LogicalMatchProgramInput {
partition_by: vec![col("k")],
order_by: vec![],
after_skip: AfterMatchSkip::PastLastRow,
pattern: Pattern::Repetition(
Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
RepetitionQuantifier::OneOrMore,
),
symbols: vec![LogicalSymbolInput::static_("A", lit(true))],
match_aware: None,
output: LogicalMatchOutput::selected_summaries(
MatchRecognizeOutputSpec::new(vec![0], vec![], vec![]),
private,
vec![LogicalSelectedMatchSummary::new(
MatchSummaryField::new(0, field),
count,
)],
),
symbol_relationships: Default::default(),
},
)?;
let batches = ctx
.execute_logical_plan(LogicalPlan::Extension(Extension {
node: Arc::new(node),
}))
.await?
.collect()
.await?;
let mut actual = Vec::new();
for batch in batches {
let keys = batch
.column(0)
.as_any()
.downcast_ref::<Float64Array>()
.unwrap();
let counts = batch
.column(1)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
for (key, count) in keys.iter().zip(counts.iter()) {
actual.push((key.unwrap().to_bits(), count));
}
}
actual.sort_unstable();
let mut expected = values.map(|key| (key, Some(1)));
expected.sort_unstable();
assert_eq!(actual, expected);
Ok(())
}
#[tokio::test]
async fn semantic_node_without_bound_source_is_rejected() -> Result<()> {
let ctx = context_with_input().await?;
let node = MatchRecognize::try_new(
LogicalPlanBuilder::empty(false)
.project(vec![lit(true).alias(crate::core::symbol_col_name("A"))])?
.build()?,
LogicalMatchProgramInput {
partition_by: vec![],
order_by: vec![],
after_skip: AfterMatchSkip::PastLastRow,
pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
symbols: vec![LogicalSymbolInput::static_("A", lit(true))],
match_aware: None,
output: LogicalMatchOutput::rows(
RowsPerMatch::OneRow,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
),
symbol_relationships: Default::default(),
},
)?;
let stripped = LogicalPlan::Extension(Extension {
node: Arc::new(node),
});
let err = to_substrait_plan_with_match_recognize(&stripped, &ctx.state())
.expect_err("semantic MR without a bound source should not export");
assert!(
err.to_string()
.contains("requires the logical node's retained BoundMatchSource"),
"{err}"
);
Ok(())
}
#[tokio::test]
async fn sql_and_substrait_sources_lower_to_same_semantics() -> Result<()> {
let ctx = context_with_input().await?;
let sql = r#"
SELECT company, last_price
FROM t
MATCH_RECOGNIZE (
PARTITION BY company ORDER BY ts
MEASURES B.price AS last_price
ONE ROW PER MATCH AFTER MATCH SKIP PAST LAST ROW
PATTERN (A B+)
DEFINE A AS price > 0, B AS B.price > 10
)"#;
let sql_plan = ctx.sql(sql).await?.logical_plan().clone();
let substrait_plan = from_substrait_plan_with_match_recognize(
&ctx.state(),
&plan_for_payload(base_payload()),
)
.await?;
let sql_node = match_recognize_node(&sql_plan).expect("SQL plan contains matcher");
let substrait_node =
match_recognize_node(&substrait_plan).expect("Substrait plan contains matcher");
assert_eq!(sql_node, substrait_node);
Ok(())
}