use super::*;
#[tokio::test]
async fn chained_one_row_and_row_stream_matchers_roundtrip() -> Result<()> {
let ctx = export_context().await?;
let chained_one_row = sql_plan(
&ctx,
r#"
WITH first_pass AS (
SELECT k, first_ts, last_price
FROM export_input
MATCH_RECOGNIZE (
PARTITION BY k
ORDER BY ts
MEASURES
FIRST(A.ts) AS first_ts,
LAST(A.price) AS last_price
ONE ROW PER MATCH
AFTER MATCH SKIP PAST LAST ROW
PATTERN (A)
DEFINE A AS price > 0
)
)
SELECT k, start_ts, peak_price, run_len
FROM first_pass
MATCH_RECOGNIZE (
PARTITION BY k
ORDER BY first_ts
MEASURES
FIRST(RISE.first_ts) AS start_ts,
LAST(RISE.last_price) AS peak_price,
COUNT(*) AS run_len
ONE ROW PER MATCH
AFTER MATCH SKIP PAST LAST ROW
PATTERN (START RISE+)
DEFINE
START AS last_price > 0,
RISE AS last_price > PREV(last_price)
)
ORDER BY k, start_ts
"#,
)
.await?;
let one_row_columns = [
("k", DataType::Int64, true),
("start_ts", DataType::Int64, true),
("peak_price", DataType::Int64, true),
("run_len", DataType::Int64, false),
];
let one_row_expected = [
vec![1_i64.into(), 2_i64.into(), 20_i64.into(), 2_i64.into()],
vec![2_i64.into(), 2_i64.into(), 7_i64.into(), 3_i64.into()],
];
let optimized = ctx.state().optimize(&chained_one_row)?;
for plan in [chained_one_row, optimized] {
assert_roundtrip_output(&ctx, plan.clone(), &one_row_columns, &one_row_expected)
.await?;
let exported = to_substrait_plan_with_match_recognize(&plan, &ctx.state())?;
let imported =
from_substrait_plan_with_match_recognize(&ctx.state(), &exported).await?;
let reoptimized = ctx.state().optimize(&imported)?;
assert_roundtrip_output(&ctx, reoptimized, &one_row_columns, &one_row_expected)
.await?;
}
let chained_all_rows = sql_plan(
&ctx,
r#"
WITH first_pass AS (
SELECT k, ts, price, mn, cls
FROM export_input
MATCH_RECOGNIZE (
PARTITION BY k
ORDER BY ts
MEASURES
MATCH_NUMBER() AS mn,
CLASSIFIER() AS cls
ALL ROWS PER MATCH
AFTER MATCH SKIP PAST LAST ROW
PATTERN (LOW HIGH)
DEFINE
LOW AS price <= 10,
HIGH AS price > 5
)
)
SELECT k, first_mn, last_cls, total_price
FROM first_pass
MATCH_RECOGNIZE (
PARTITION BY k
ORDER BY ts
MEASURES
FIRST(S.mn) AS first_mn,
LAST(S.cls) AS last_cls,
SUM(DISTINCT S.price) AS total_price
ONE ROW PER MATCH
PATTERN (S+)
DEFINE S AS mn >= 1
)
ORDER BY k
"#,
)
.await?;
let all_rows_columns = [
("k", DataType::Int64, true),
("first_mn", DataType::Int64, true),
("last_cls", DataType::Utf8, true),
("total_price", DataType::Int64, true),
];
let all_rows_expected = [
vec![1_i64.into(), 1_i64.into(), "HIGH".into(), 30_i64.into()],
vec![2_i64.into(), 1_i64.into(), "HIGH".into(), 11_i64.into()],
];
let optimized = ctx.state().optimize(&chained_all_rows)?;
for plan in [chained_all_rows, optimized] {
assert_roundtrip_output(&ctx, plan, &all_rows_columns, &all_rows_expected)
.await?;
}
Ok(())
}
#[tokio::test]
async fn aliased_reserved_inputs_and_table_symbol_qualifiers_roundtrip() -> Result<()> {
let ctx = export_context().await?;
ctx.register_batch(
"__mr_raw_source",
RecordBatch::try_new(
Arc::new(Schema::new(vec![
Field::new("ts", DataType::Int64, false),
Field::new("__mr_value", DataType::Int64, false),
])),
vec![
Arc::new(Int64Array::from(vec![1, 2, 3])),
Arc::new(Int64Array::from(vec![10, 20, 30])),
],
)?,
)?;
let aliased_reserved = sql_plan(
&ctx,
r#"
WITH clean AS (
SELECT ts, __mr_value AS v FROM __mr_raw_source
)
SELECT last_v, cnt
FROM clean
MATCH_RECOGNIZE (
ORDER BY ts
MEASURES LAST(A.v) AS last_v, COUNT(*) AS cnt
ONE ROW PER MATCH
PATTERN (A+)
DEFINE A AS v >= 10
)
"#,
)
.await?;
for plan in [
aliased_reserved.clone(),
ctx.state().optimize(&aliased_reserved)?,
] {
assert_roundtrip_output(
&ctx,
plan,
&[
("last_v", DataType::Int64, true),
("cnt", DataType::Int64, false),
],
&[vec![30_i64.into(), 3_i64.into()]],
)
.await?;
}
let aliased_qualifier = sql_plan(
&ctx,
r#"
WITH clean AS (
SELECT company, ts, price FROM t
)
SELECT company, cnt
FROM clean
MATCH_RECOGNIZE (
PARTITION BY company
ORDER BY ts
MEASURES COUNT(*) AS cnt
ONE ROW PER MATCH
PATTERN (t+)
DEFINE t AS price > 0
)
"#,
)
.await?;
for plan in [
aliased_qualifier.clone(),
ctx.state().optimize(&aliased_qualifier)?,
] {
assert_roundtrip_output(
&ctx,
plan,
&[
("company", DataType::Utf8, true),
("cnt", DataType::Int64, false),
],
&[vec!["acme".into(), 3_i64.into()]],
)
.await?;
}
let exported =
to_substrait_plan_with_match_recognize(&aliased_reserved, &ctx.state())?;
let mut complete = root_payload(&exported)?;
complete.semantic_node = false;
complete.semantic_node_finalizes_one_row = false;
complete.retained_passthrough_input_fields.clear();
complete.prepared_output_fields.clear();
complete.summary_output_fields.clear();
complete
.required_features
.retain(|feature| feature != DATAFUSION_SEMANTIC_ONE_ROW_FEATURE);
let mut complete_plan = (*exported).clone();
complete_plan.relations = plan_for_payload(complete).relations;
let Some(plan_rel::RelType::Rel(root)) = &mut complete_plan.relations[0].rel_type
else {
panic!("expected root relation");
};
let Some(RelType::ExtensionSingle(extension)) = &mut root.rel_type else {
panic!("expected extension relation");
};
let Some(RelType::Read(read)) = &mut extension.input.as_mut().unwrap().rel_type
else {
panic!("expected read relation");
};
read.read_type = Some(ReadType::NamedTable(NamedTable {
names: vec!["__mr_raw_source".to_string()],
advanced_extension: None,
}));
read.base_schema = Some(named_struct(vec![
("ts", i64_type()),
("__mr_value", i64_type()),
]));
let error = from_substrait_plan_with_match_recognize(&ctx.state(), &complete_plan)
.await
.unwrap_err();
assert!(
error.to_string().contains("reserved internal prefix"),
"{error}"
);
Ok(())
}
#[tokio::test]
async fn one_row_summary_roundtrip_preserves_identities_across_stored_column_shifts()
-> Result<()> {
let builder =
datafusion::execution::SessionStateBuilder::new().with_default_features();
let ctx = new_match_recognize_context(builder)?;
ctx.register_batch(
"t",
RecordBatch::try_new(
Arc::new(Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("k", DataType::Int64, false),
Field::new("ts", DataType::Int64, false),
])),
vec![
Arc::new(Int64Array::from(vec![1, 2, 3, 4])),
Arc::new(Int64Array::from(vec![1, 1, 1, 2])),
Arc::new(Int64Array::from(vec![1, 2, 10, 3])),
],
)?,
)?;
let direct_unreferenced_id = sql_plan(
&ctx,
"SELECT * FROM t AS clean MATCH_RECOGNIZE (
ORDER BY ts
MEASURES COUNT(t.id) AS c1, COUNT(t.*) AS c2, COUNT(u.*) AS c3
ONE ROW PER MATCH
PATTERN (t+ u*)
DEFINE t AS ts < 10, u AS ts >= 10
)",
)
.await?;
assert_roundtrip_output(
&ctx,
direct_unreferenced_id,
&[
("c1", DataType::Int64, false),
("c2", DataType::Int64, false),
("c3", DataType::Int64, false),
],
&[vec![3_i64.into(), 3_i64.into(), 1_i64.into()]],
)
.await?;
for (sql, columns, expected_rows) in [
(
"SELECT * FROM t AS clean MATCH_RECOGNIZE (
ORDER BY ts
MEASURES COUNT(t.id) AS c1, COUNT(t.*) AS c2, COUNT(u.*) AS c3
ONE ROW PER MATCH
PATTERN (t+ u*)
DEFINE t AS id > 0 AND ts < 10, u AS ts >= 10
)",
vec![
("c1", DataType::Int64, false),
("c2", DataType::Int64, false),
("c3", DataType::Int64, false),
],
vec![vec![3_i64.into(), 3_i64.into(), 1_i64.into()]],
),
(
"SELECT * FROM t AS clean MATCH_RECOGNIZE (
ORDER BY ts
MEASURES COUNT(t.id) AS c1, SUM(u.ts) AS s2
ONE ROW PER MATCH
PATTERN (t+ u*)
DEFINE t AS id > 0 AND ts < 10, u AS ts >= 10
)",
vec![
("c1", DataType::Int64, false),
("s2", DataType::Int64, true),
],
vec![vec![3_i64.into(), 10_i64.into()]],
),
(
"WITH clean AS (SELECT id, ts FROM t)
SELECT c2 FROM clean MATCH_RECOGNIZE (
ORDER BY ts
MEASURES COUNT(A.id) AS c1, COUNT(A.*) AS c2, COUNT(B.*) AS c3
ONE ROW PER MATCH
PATTERN (A+ B*)
DEFINE A AS id > 0 AND ts < 10, B AS ts >= 10
)",
vec![("c2", DataType::Int64, false)],
vec![vec![3_i64.into()]],
),
(
"WITH clean AS (SELECT id, ts FROM t)
SELECT * FROM clean MATCH_RECOGNIZE (
ORDER BY ts
MEASURES COUNT(A.id) AS c1, COUNT(A.*) AS c2, COUNT(B.*) AS c3
ONE ROW PER MATCH
PATTERN (A+ B*)
DEFINE A AS ts < 10, B AS ts >= 10
)",
vec![
("c1", DataType::Int64, false),
("c2", DataType::Int64, false),
("c3", DataType::Int64, false),
],
vec![vec![3_i64.into(), 3_i64.into(), 1_i64.into()]],
),
(
"WITH clean AS (SELECT id + 0 AS id, ts FROM t)
SELECT c2 FROM clean MATCH_RECOGNIZE (
ORDER BY ts
MEASURES COUNT(A.id) AS c1, COUNT(A.*) AS c2, COUNT(B.*) AS c3
ONE ROW PER MATCH
PATTERN (A+ B*)
DEFINE A AS id > 0 AND ts < 10, B AS ts >= 10
)",
vec![("c2", DataType::Int64, false)],
vec![vec![3_i64.into()]],
),
(
"WITH clean AS (SELECT id + 0 AS id, ts FROM t)
SELECT * FROM clean MATCH_RECOGNIZE (
ORDER BY ts
MEASURES COUNT(A.id) AS c1, COUNT(A.*) AS c2, COUNT(B.*) AS c3
ONE ROW PER MATCH
PATTERN (A+ B*)
DEFINE A AS ts < 10, B AS ts >= 10
)",
vec![
("c1", DataType::Int64, false),
("c2", DataType::Int64, false),
("c3", DataType::Int64, false),
],
vec![vec![3_i64.into(), 3_i64.into(), 1_i64.into()]],
),
(
"SELECT k, c1, c2, c3 FROM t MATCH_RECOGNIZE (
PARTITION BY k ORDER BY ts
MEASURES COUNT(A.id) AS c1, COUNT(A.*) AS c2, COUNT(B.*) AS c3
ONE ROW PER MATCH
PATTERN (A+ B*)
DEFINE A AS id > 0 AND ts < 10, B AS ts >= 10
) WHERE k = 1",
vec![
("k", DataType::Int64, true),
("c1", DataType::Int64, false),
("c2", DataType::Int64, false),
("c3", DataType::Int64, false),
],
vec![vec![1_i64.into(), 2_i64.into(), 2_i64.into(), 1_i64.into()]],
),
] {
let direct = sql_plan(&ctx, sql).await?;
for plan in [direct.clone(), ctx.state().optimize(&direct)?] {
assert_roundtrip_output(&ctx, plan, &columns, &expected_rows).await?;
}
}
Ok(())
}
#[tokio::test]
async fn structured_struct_casts_export_only_names_a_bare_type_preserves() -> Result<()> {
let ctx = context_with_input().await?;
for (fields, preserved) in [(["c0", "c1"], true), (["x", "y"], false)] {
let [first, second] = fields;
let cast = format!("CAST(A.s AS STRUCT<{first} BIGINT, {second} BIGINT>)");
for (measure, define) in [
(cast.as_str(), "true".to_string()),
("LAST(A.ts)", format!("{cast} IS NOT NULL")),
] {
let sql = format!(
"WITH src AS (
SELECT ts, named_struct('{first}', price, '{second}', ts) AS s FROM t)
SELECT v FROM src MATCH_RECOGNIZE (
ORDER BY ts MEASURES {measure} AS v
ONE ROW PER MATCH PATTERN (A+) DEFINE A AS {define})"
);
let plan = sql_plan(&ctx, &sql).await?;
if preserved {
assert_eq!(
roundtrip_rows(&ctx, &plan).await?,
plan_rows(&ctx, plan).await?,
"{sql}"
);
} else {
assert_export_rejected(&ctx, &plan, "cannot preserve CAST target type");
}
}
}
Ok(())
}
#[tokio::test]
async fn structured_timestamptz_casts_require_utc_timezone() -> Result<()> {
let ctx = context_with_input().await?;
for (tz, preserved) in [
("UTC", true),
("America/New_York", false),
("+02:00", false),
] {
ctx.sql(&format!("SET datafusion.execution.time_zone = '{tz}'"))
.await?
.collect()
.await?;
let cast = "CAST(A.ts_text AS TIMESTAMPTZ)";
for (measure, define) in [
(cast, "true".to_string()),
("LAST(A.ts)", format!("{cast} IS NOT NULL")),
] {
let sql = format!(
"WITH src AS (
SELECT ts, '2024-01-01 00:00:00' AS ts_text FROM t)
SELECT v FROM src MATCH_RECOGNIZE (
ORDER BY ts MEASURES {measure} AS v
ONE ROW PER MATCH PATTERN (A+) DEFINE A AS {define})"
);
let plan = sql_plan(&ctx, &sql).await?;
if preserved {
assert_eq!(
roundtrip_rows(&ctx, &plan).await?,
plan_rows(&ctx, plan).await?,
"{tz}: {sql}"
);
} else {
assert_export_rejected(&ctx, &plan, "cannot preserve CAST target type");
}
}
}
Ok(())
}
#[tokio::test]
async fn normalize_summary_expr_desugars_simple_case_before_child_literal_rewrites()
-> Result<()> {
use crate::substrait::consumer::normalize_wire_expr;
use datafusion::common::ScalarValue;
let ctx = context_with_input().await?;
let state = ctx.state();
let summary_schema = Arc::new(DFSchema::try_from(Schema::new(vec![
Field::new("price", DataType::Int64, true),
Field::new("d", DataType::Date64, true),
Field::new("v", DataType::Int64, true),
]))?);
let simple_case = |base: Expr, when: Expr, then: Expr, else_expr: Option<Expr>| {
Expr::Case(expr::Case {
expr: Some(Box::new(base)),
when_then_expr: vec![(Box::new(when), Box::new(then))],
else_expr: else_expr.map(Box::new),
})
};
let arm_count = |expression: &Expr| match expression {
Expr::Case(case) => {
assert!(case.expr.is_none(), "expected searched CASE: {case:?}");
case.when_then_expr.len()
}
other => panic!("expected CASE expression, got {other:?}"),
};
let cases = [
(
"date64 literal with else",
simple_case(
col("d"),
lit(ScalarValue::Date64(Some(86_400_000))),
lit(1_i64),
Some(lit(0_i64)),
),
1,
1,
),
(
"date64 literal without else",
simple_case(
col("d"),
lit(ScalarValue::Date64(Some(86_400_000))),
lit(1_i64),
None,
),
1,
1,
),
(
"cast untyped null with else",
simple_case(
col("price"),
Expr::Cast(expr::Cast::new(
Box::new(lit(ScalarValue::Null)),
DataType::Int64,
)),
lit(1_i64),
Some(lit(0_i64)),
),
2,
1,
),
(
"cast untyped null without else",
simple_case(
col("price"),
Expr::Cast(expr::Cast::new(
Box::new(lit(ScalarValue::Null)),
DataType::Int64,
)),
lit(1_i64),
None,
),
2,
1,
),
(
"aliased non-null literal preserves guard",
simple_case(
col("price"),
lit(1_i64).alias("a"),
lit(10_i64),
Some(lit(0_i64)),
),
2,
2,
),
(
"non-inert arithmetic preserves guard",
simple_case(
col("price"),
col("v") + lit(1_i64),
lit(1_i64),
Some(lit(0_i64)),
),
2,
2,
),
(
"nested simple case with cast null and date64",
simple_case(
simple_case(
col("price"),
Expr::Cast(expr::Cast::new(
Box::new(lit(ScalarValue::Null)),
DataType::Int64,
)),
lit(1_i64),
Some(lit(2_i64)),
),
lit(1_i64),
simple_case(
col("d"),
lit(ScalarValue::Date64(Some(86_400_000))),
lit(10_i64),
Some(lit(20_i64)),
),
Some(lit(0_i64)),
),
1,
1,
),
];
for (label, expression, expected_wire_arms, expected_normalized_arms) in cases {
let mut producer = MatchRecognizeSubstraitProducer::new(&state);
let encoded = producer.handle_expr(&expression, &summary_schema)?;
let extensions = producer.get_extensions();
let consumer = MatchRecognizeSubstraitConsumer::new(&extensions, &state);
let decoded = consumer
.consume_expression(&encoded, summary_schema.as_ref())
.await?;
assert_eq!(arm_count(&decoded), expected_wire_arms, "{label} wire arms");
let normalized_planned =
normalize_wire_expr(expression, summary_schema.as_ref())?;
let normalized_decoded = normalize_wire_expr(decoded, summary_schema.as_ref())?;
assert_eq!(
arm_count(&normalized_planned),
expected_normalized_arms,
"{label} normalized arms"
);
assert_eq!(
normalized_planned, normalized_decoded,
"{label}: planned and wire-decoded summary identities must match"
);
}
Ok(())
}
#[tokio::test]
async fn one_row_case_summary_roundtrips_date64_and_cast_null_when_operands() -> Result<()>
{
use crate::core::RepetitionQuantifier;
use crate::planning::{
DefaultMatchRecognizePlanningContext, plan_match_recognize_from_source,
};
use datafusion::arrow::array::Date64Array;
use datafusion::common::ScalarValue;
let ctx = context_with_input().await?;
ctx.register_batch(
"case_null_input",
RecordBatch::try_from_iter([
("ts", Arc::new(Int64Array::from(vec![1, 2, 3])) as ArrayRef),
(
"price",
Arc::new(Int64Array::from(vec![Some(10), None, Some(14)])) as ArrayRef,
),
])?,
)?;
let direct_cast_null = sql_plan(
&ctx,
"SELECT total, without_else
FROM case_null_input MATCH_RECOGNIZE (
ORDER BY ts
MEASURES
CASE LAST(A.price) WHEN CAST(NULL AS BIGINT) THEN 1 ELSE 2 END AS total,
CASE LAST(A.price) WHEN CAST(NULL AS BIGINT) THEN 1 END AS without_else
ONE ROW PER MATCH
PATTERN (A+)
DEFINE A AS true
)",
)
.await?;
assert!(
match_recognize_node(&direct_cast_null)
.expect("one-row matcher")
.program()
.output()
.finalizes_selected_summaries()
);
let cast_null_columns = [
("total", DataType::Int64, false),
("without_else", DataType::Int64, true),
];
let cast_null_expected = [vec![2_i64.into(), ScalarValue::Int64(None)]];
for plan in [
direct_cast_null.clone(),
ctx.state().optimize(&direct_cast_null)?,
] {
assert_roundtrip_output(&ctx, plan, &cast_null_columns, &cast_null_expected)
.await?;
}
ctx.register_batch(
"date64_case_input",
RecordBatch::try_from_iter([
("ord", Arc::new(Int64Array::from(vec![1, 2, 3])) as ArrayRef),
(
"value",
Arc::new(Date64Array::from(vec![
Some(86_400_000_i64),
None,
Some(172_800_000_i64),
])) as ArrayRef,
),
])?,
)?;
let date64_input = ctx.table("date64_case_input").await?.logical_plan().clone();
let date64_case_summary = |else_expr: Option<BoundMatchExpr>| BoundMatchExpr::Case {
expr: Some(Box::new(BoundMatchExpr::Navigation(
MatchNavigation::Last {
expr: Box::new(BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".to_string(),
column: Column::from_name("value"),
})),
offset: None,
},
))),
when_then: vec![(
BoundMatchExpr::Literal(ScalarValue::Date64(Some(172_800_000))),
BoundMatchExpr::Literal(ScalarValue::Int64(Some(10))),
)],
else_expr: else_expr.map(Box::new),
};
let date64_spec = BoundMatchSpec {
partition_by: vec![],
order_by: vec![MatchRecognizeSortExpr {
expr: BoundMatchExpr::InputColumn(Column::from_name("ord")),
direction: MatchRecognizeSortDirection::Asc,
null_ordering: MatchRecognizeNullOrdering::Last,
}],
source_rows_per_match: RowsPerMatch::OneRow,
after_match_skip: AfterMatchSkip::PastLastRow,
pattern: Pattern::Repetition(
Box::new(Pattern::Symbol(Symbol::Named("A".to_string()))),
RepetitionQuantifier::OneOrMore,
),
symbols: vec!["A".to_string()],
definitions: vec![MatchRecognizeDefinition {
symbol: "A".to_string(),
predicate: BoundMatchExpr::Literal(ScalarValue::Boolean(Some(true))),
}],
measures: vec![
MatchRecognizeMeasure {
name: Some("matched_with_else".to_string()),
expression: date64_case_summary(Some(BoundMatchExpr::Literal(
ScalarValue::Int64(Some(1)),
))),
},
MatchRecognizeMeasure {
name: Some("matched_without_else".to_string()),
expression: date64_case_summary(None),
},
],
output: MatchRecognizeOutputContract::Derived,
};
let date64_plan = plan_match_recognize_from_source(
&mut DefaultMatchRecognizePlanningContext::new(),
date64_input,
date64_spec,
)?;
assert!(
match_recognize_node(&date64_plan)
.expect("date64 one-row matcher")
.program()
.output()
.finalizes_selected_summaries()
);
let date64_columns = [
("matched_with_else", DataType::Int64, false),
("matched_without_else", DataType::Int64, true),
];
let date64_expected = [vec![10_i64.into(), 10_i64.into()]];
for plan in [date64_plan.clone(), ctx.state().optimize(&date64_plan)?] {
assert_roundtrip_output(&ctx, plan, &date64_columns, &date64_expected).await?;
}
Ok(())
}
#[tokio::test]
async fn one_row_colliding_non_volatile_summaries_roundtrip() -> Result<()> {
let ctx = context_with_input().await?;
let body = "FROM t MATCH_RECOGNIZE (
ORDER BY ts
MEASURES
SUM(CASE A.price WHEN 10 THEN 1 ELSE 0 END) AS s1,
SUM(CASE WHEN A.price = 10 THEN 1 ELSE 0 END) AS s2,
SUM(CASE WHEN A.price BETWEEN 10 AND 12 THEN 1 ELSE 0 END) AS b1,
SUM(CASE WHEN A.price >= 10 AND A.price <= 12 THEN 1 ELSE 0 END) AS b2
ONE ROW PER MATCH
PATTERN (A+)
DEFINE A AS true
)";
let ordinary = sql_plan(&ctx, &format!("SELECT s1, s2, b1, b2 {body}")).await?;
let source = match_recognize_node(&ordinary)
.expect("one-row matcher")
.bound_source()
.expect("bound source");
let native = 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 node = match_recognize_node(&native).expect("native one-row matcher");
assert!(node.program().output().finalizes_selected_summaries());
let summary_cols: Vec<String> = node
.program()
.selected_match_summaries()
.iter()
.map(|summary| summary.column_name())
.collect();
assert_eq!(summary_cols.len(), 4);
let direct = LogicalPlanBuilder::from(native.clone())
.project(vec![
col(&summary_cols[0]).alias("s1"),
col(&summary_cols[1]).alias("s2"),
col(&summary_cols[2]).alias("b1"),
col(&summary_cols[3]).alias("b2"),
])?
.build()?;
let columns = [
("s1", DataType::Int64, true),
("s2", DataType::Int64, true),
("b1", DataType::Int64, true),
("b2", DataType::Int64, true),
];
let expected = [vec![1_i64.into(), 1_i64.into(), 2_i64.into(), 2_i64.into()]];
for plan in [direct.clone(), ctx.state().optimize(&direct)?] {
assert_roundtrip_output(&ctx, plan, &columns, &expected).await?;
}
let pruned = LogicalPlanBuilder::from(native)
.project(vec![
col(&summary_cols[1]).alias("s2"),
col(&summary_cols[3]).alias("b2"),
])?
.build()?;
let pruned_optimized = ctx.state().optimize(&pruned)?;
let pruned_node =
match_recognize_node(&pruned_optimized).expect("pruned one-row matcher");
assert!(
pruned_node
.program()
.output()
.finalizes_selected_summaries()
);
assert_eq!(pruned_node.program().selected_match_summaries().len(), 2);
let pruned_columns = [("s2", DataType::Int64, true), ("b2", DataType::Int64, true)];
let pruned_expected = [vec![1_i64.into(), 2_i64.into()]];
for plan in [pruned, pruned_optimized] {
assert_roundtrip_output(&ctx, plan, &pruned_columns, &pruned_expected).await?;
}
Ok(())
}
#[tokio::test]
async fn prepared_window_desugared_exprs_roundtrip() -> Result<()> {
let ctx = context_with_input().await?;
let cases = [
(
"SELECT ts FROM t MATCH_RECOGNIZE (
ORDER BY ts ALL ROWS PER MATCH PATTERN (A+)
DEFINE A AS PREV(A.price BETWEEN 10 AND 20)
)",
1_usize,
true,
vec![vec![2_i64.into()], vec![3_i64.into()]],
),
(
"SELECT ts FROM t MATCH_RECOGNIZE (
ORDER BY ts ALL ROWS PER MATCH PATTERN (A+)
DEFINE A AS PREV(A.price NOT BETWEEN 12 AND 14)
)",
1_usize,
true,
vec![vec![2_i64.into()]],
),
(
"SELECT ts FROM t MATCH_RECOGNIZE (
ORDER BY ts ALL ROWS PER MATCH PATTERN (A+)
DEFINE A AS PREV(CASE A.price WHEN 10 THEN 1 ELSE 0 END) = 1
)",
1_usize,
true,
vec![vec![2_i64.into()]],
),
(
"SELECT ts FROM t MATCH_RECOGNIZE (
ORDER BY ts ALL ROWS PER MATCH PATTERN (A+)
DEFINE A AS PREV(A.price NOT IN (12, 14))
)",
1_usize,
true,
vec![vec![2_i64.into()]],
),
(
"SELECT ts FROM t MATCH_RECOGNIZE (
ORDER BY ts ALL ROWS PER MATCH PATTERN (A+)
DEFINE A AS PREV(A.price BETWEEN 10 AND 20)
AND PREV(10 <= A.price AND A.price <= 20)
)",
2_usize,
false,
vec![vec![2_i64.into()], vec![3_i64.into()]],
),
];
for (sql, expected_prepared_count, test_optimized, expected_rows) in cases {
let direct = sql_plan(&ctx, sql).await?;
let exported = to_substrait_plan_with_match_recognize(&direct, &ctx.state())?;
let semantic = root_payload(&exported)?;
assert_eq!(
semantic.prepared_output_fields.len(),
expected_prepared_count
);
let mut plans = vec![direct.clone()];
if test_optimized {
plans.push(ctx.state().optimize(&direct)?);
}
for plan in plans {
assert_roundtrip_output(
&ctx,
plan,
&[("ts", DataType::Int64, true)],
&expected_rows,
)
.await?;
}
}
Ok(())
}
#[tokio::test]
async fn logical_offset_and_compound_navigation_roundtrip_sql_execution() -> Result<()> {
let ctx = export_context().await?;
for (sql, expect_logical_feature, expect_compound_feature) in [
(
"SELECT k, f1, l1, pf1, nl1
FROM export_input
MATCH_RECOGNIZE (
PARTITION BY k
ORDER BY ts
MEASURES
FIRST(A.price, 1) AS f1,
LAST(A.price, 1) AS l1,
PREV(FIRST(A.price, 1), 1, -1) AS pf1,
NEXT(LAST(A.price, 1), 1, -1) AS nl1
ONE ROW PER MATCH
PATTERN (A+)
DEFINE A AS TRUE
)
ORDER BY k",
true,
true,
),
(
"SELECT k, ts, f1, l1
FROM export_input
MATCH_RECOGNIZE (
PARTITION BY k
ORDER BY ts
MEASURES
FIRST(price, 1) AS f1,
LAST(price, 1) AS l1
ALL ROWS PER MATCH
PATTERN (A+)
DEFINE A AS TRUE
)
ORDER BY k, ts",
true,
false,
),
(
"SELECT k, ts, pf
FROM export_input
MATCH_RECOGNIZE (
PARTITION BY k
ORDER BY ts
MEASURES
PREV(FIRST(A.price), 1, -9) AS pf
ALL ROWS PER MATCH
PATTERN (A+)
DEFINE A AS ts >= 2
)
ORDER BY k, ts",
false,
true,
),
(
"SELECT k, ts, price
FROM export_input
MATCH_RECOGNIZE (
PARTITION BY k
ORDER BY ts
ALL ROWS PER MATCH
PATTERN (A B+)
DEFINE
A AS ts = 1,
B AS LAST(price, 1) IS NOT NULL
AND PREV(FIRST(A.price), 1, -1) = -1
)
ORDER BY k, ts",
true,
true,
),
] {
let direct = sql_plan(&ctx, sql).await?;
let state = ctx.state();
for plan in [direct.clone(), state.optimize(&direct)?] {
let exported = to_substrait_plan_with_match_recognize(&plan, &state)?;
let payload = root_payload(&exported)?;
assert_eq!(
payload
.required_features
.iter()
.any(|f| f == MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE),
expect_logical_feature,
"logical feature mismatch for: {sql}"
);
assert_eq!(
payload
.required_features
.iter()
.any(|f| f == MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE),
expect_compound_feature,
"compound feature mismatch for: {sql}"
);
let imported =
from_substrait_plan_with_match_recognize(&state, &exported).await?;
assert_eq!(
plan_rows(&ctx, imported).await?,
plan_rows(&ctx, plan).await?,
"{sql}"
);
}
}
Ok(())
}
#[tokio::test]
async fn analyzed_and_optimized_prepared_define_windows_roundtrip_substrait() -> Result<()>
{
use datafusion::arrow::array::Int32Array;
let ctx = context_with_input().await?;
ctx.register_batch(
"coerced_input",
RecordBatch::try_from_iter([
(
"k",
Arc::new(Int64Array::from(vec![1, 1, 1, 1])) as ArrayRef,
),
(
"ts",
Arc::new(Int64Array::from(vec![1, 2, 3, 4])) as ArrayRef,
),
(
"val32",
Arc::new(Int32Array::from(vec![0, 5, 10, 15])) as ArrayRef,
),
])?,
)?;
let state = ctx.state();
for (label, sql) in [
(
"coerced_prev_eq_int32",
"SELECT k, ts, val32
FROM coerced_input
MATCH_RECOGNIZE (
PARTITION BY k
ORDER BY ts
ALL ROWS PER MATCH
PATTERN (A+)
DEFINE A AS PREV(val32 = 0) IS NULL OR val32 > 0
)
ORDER BY k, ts",
),
(
"simplified_prev_not_eq",
"SELECT k, ts, val32
FROM coerced_input
MATCH_RECOGNIZE (
PARTITION BY k
ORDER BY ts
ALL ROWS PER MATCH
PATTERN (A+)
DEFINE A AS PREV(NOT (val32 = 10)) IS NULL OR val32 >= 0
)
ORDER BY k, ts",
),
(
"coerced_input_window_sum",
"SELECT k, ts, val32
FROM coerced_input
MATCH_RECOGNIZE (
PARTITION BY k
ORDER BY ts
ALL ROWS PER MATCH
PATTERN (A+)
DEFINE A AS SUM(val32) OVER () > 0
)
ORDER BY k, ts",
),
] {
let direct = sql_plan(&ctx, sql).await?;
let analyzed = state.analyzer().execute_and_check(
direct.clone(),
state.config_options(),
|_, _| {},
)?;
let simplified = datafusion::optimizer::Optimizer::with_rules(vec![Arc::new(
datafusion::optimizer::simplify_expressions::SimplifyExpressions::new(),
)])
.optimize(analyzed.clone(), &state, |_, _| {})?;
let optimized = state.optimize(&direct)?;
for (stage, plan, expect_prepared) in [
("direct", direct, true),
("analyzed", analyzed, true),
("simplified", simplified, true),
("optimized", optimized, false),
] {
let exported = to_substrait_plan_with_match_recognize(&plan, &state)?;
if expect_prepared {
assert!(
!root_payload(&exported)?.prepared_output_fields.is_empty(),
"{label} ({stage}): expected retained prepared window field"
);
}
let imported =
from_substrait_plan_with_match_recognize(&state, &exported).await?;
assert_eq!(
plan_rows(&ctx, imported).await?,
plan_rows(&ctx, plan).await?,
"{label} ({stage})"
);
}
}
Ok(())
}
#[tokio::test]
async fn bare_decoded_wire_types_roundtrip_prepared_windows_and_one_row_summaries()
-> Result<()> {
use datafusion::arrow::array::{ListArray, StructArray, TimestampMicrosecondArray};
use datafusion::arrow::buffer::OffsetBuffer;
use datafusion::arrow::datatypes::{Field, Fields, Schema, TimeUnit};
let struct_fields = Fields::from(vec![
Field::new("x", DataType::Int64, true),
Field::new("y", DataType::Int64, true),
]);
let list_item = Arc::new(Field::new("elem", DataType::Int64, false));
let tz_type =
DataType::Timestamp(TimeUnit::Microsecond, Some("America/New_York".into()));
let schema = Arc::new(Schema::new(vec![
Field::new("ts", DataType::Int64, true),
Field::new("s", DataType::Struct(struct_fields.clone()), true),
Field::new("tz", tz_type.clone(), true),
Field::new("lst", DataType::List(Arc::clone(&list_item)), true),
]));
let s = Arc::new(StructArray::new(
struct_fields,
vec![
Arc::new(Int64Array::from(vec![10, 20, 30])) as ArrayRef,
Arc::new(Int64Array::from(vec![Some(1), None, Some(3)])) as ArrayRef,
],
None,
));
let tz = Arc::new(
TimestampMicrosecondArray::from(vec![Some(1_000), Some(2_000), Some(3_000)])
.with_timezone("America/New_York"),
);
let lst = Arc::new(ListArray::new(
list_item,
OffsetBuffer::new(vec![0, 1, 2, 3].into()),
Arc::new(Int64Array::from(vec![100, 200, 300])),
None,
));
let batch = RecordBatch::try_new(
schema,
vec![
Arc::new(Int64Array::from(vec![Some(1), Some(2), Some(3)])),
s,
tz,
lst,
],
)?;
let ctx = context_with_input().await?;
ctx.register_batch("rich_types", batch)?;
let state = ctx.state();
for col_name in ["s", "tz", "lst"] {
let define_sql = format!(
"SELECT ts
FROM rich_types
MATCH_RECOGNIZE (
ORDER BY ts
ALL ROWS PER MATCH
PATTERN (A+)
DEFINE A AS PREV(CASE (A.ts > 0) WHEN (A.ts = 1) THEN A.{col_name} END) IS NULL
OR A.ts > 0
)
ORDER BY ts"
);
let direct = sql_plan(&ctx, &define_sql).await?;
let analyzed = state.analyzer().execute_and_check(
direct.clone(),
state.config_options(),
|_, _| {},
)?;
for (stage, plan) in [("direct", direct), ("analyzed", analyzed)] {
let exported = to_substrait_plan_with_match_recognize(&plan, &state)?;
assert!(
!root_payload(&exported)?.prepared_output_fields.is_empty(),
"define {col_name} ({stage}): expected retained prepared window field"
);
let imported =
from_substrait_plan_with_match_recognize(&state, &exported).await?;
assert_eq!(
plan_rows(&ctx, imported).await?,
plan_rows(&ctx, plan).await?,
"define {col_name} ({stage})"
);
}
let one_row_sql = format!(
"SELECT mn, picked
FROM rich_types
MATCH_RECOGNIZE (
ORDER BY ts
MEASURES
MATCH_NUMBER() AS mn,
FIRST(CASE (A.ts > 0) WHEN (A.ts = 1) THEN A.{col_name} END) AS picked
ONE ROW PER MATCH
PATTERN (A+)
DEFINE A AS ts > 0
)
ORDER BY mn"
);
let ordinary = sql_plan(&ctx, &one_row_sql).await?;
let source = match_recognize_node(&ordinary)
.expect("one-row matcher")
.bound_source()
.expect("bound source");
let native =
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 optimized_native = state.optimize(&native)?;
for (stage, plan) in [("direct", native), ("optimized", optimized_native)] {
let exported = to_substrait_plan_with_match_recognize(&plan, &state)?;
assert!(
!root_payload(&exported)?.summary_output_fields.is_empty(),
"one_row {col_name} ({stage}): expected summary_output_fields"
);
let imported =
from_substrait_plan_with_match_recognize(&state, &exported).await?;
assert_eq!(
plan_rows(&ctx, imported).await?,
plan_rows(&ctx, plan).await?,
"one_row {col_name} ({stage})"
);
}
}
Ok(())
}
#[tokio::test]
async fn compound_non_null_literal_defaults_roundtrip_prepared_windows_and_one_row_summaries()
-> Result<()> {
use datafusion::arrow::array::{ListArray, StructArray};
use datafusion::arrow::buffer::OffsetBuffer;
use datafusion::arrow::datatypes::{Field, Fields, Schema};
let struct_fields = Fields::from(vec![
Field::new("x", DataType::Int64, true),
Field::new("y", DataType::Int64, true),
]);
let list_item = Arc::new(Field::new("elem", DataType::Int64, false));
let schema = Arc::new(Schema::new(vec![
Field::new("ts", DataType::Int64, false),
Field::new("s", DataType::Struct(struct_fields.clone()), true),
Field::new("lst", DataType::List(Arc::clone(&list_item)), true),
]));
let s = Arc::new(StructArray::new(
struct_fields,
vec![
Arc::new(Int64Array::from(vec![10, 20, 30])) as ArrayRef,
Arc::new(Int64Array::from(vec![Some(1), None, Some(3)])) as ArrayRef,
],
None,
));
let lst = Arc::new(ListArray::new(
list_item,
OffsetBuffer::new(vec![0, 1, 2, 3].into()),
Arc::new(Int64Array::from(vec![100, 200, 300])),
None,
));
let batch = RecordBatch::try_new(
schema,
vec![Arc::new(Int64Array::from(vec![1, 2, 3])), s, lst],
)?;
let ctx = context_with_input().await?;
ctx.register_batch("compound_defaults", batch)?;
let state = ctx.state();
for (label, define_expr) in [
(
"struct_default",
"PREV(s, 1, named_struct('x', CAST(0 AS BIGINT), 'y', CAST(NULL AS BIGINT))) IS NOT NULL",
),
(
"list_default",
"PREV(lst, 1, make_array(CAST(1 AS BIGINT), CAST(2 AS BIGINT))) IS NOT NULL",
),
] {
let sql = format!(
"SELECT ts
FROM compound_defaults
MATCH_RECOGNIZE (
ORDER BY ts
ALL ROWS PER MATCH
PATTERN (A+)
DEFINE A AS {define_expr}
)
ORDER BY ts"
);
let direct = sql_plan(&ctx, &sql).await?;
let analyzed = state.analyzer().execute_and_check(
direct.clone(),
state.config_options(),
|_, _| {},
)?;
for (stage, plan) in [("direct", direct), ("analyzed", analyzed)] {
let exported = to_substrait_plan_with_match_recognize(&plan, &state)?;
assert!(
!root_payload(&exported)?.prepared_output_fields.is_empty(),
"{label} ({stage}): expected retained prepared window field"
);
let imported =
from_substrait_plan_with_match_recognize(&state, &exported).await?;
assert_eq!(
plan_rows(&ctx, imported).await?,
plan_rows(&ctx, plan).await?,
"{label} ({stage})"
);
}
}
let one_row_sql = "SELECT mn
FROM compound_defaults
MATCH_RECOGNIZE (
ORDER BY ts
MEASURES
MATCH_NUMBER() AS mn,
PREV(A.s, 1, named_struct('x', CAST(0 AS BIGINT), 'y', CAST(NULL AS BIGINT))) AS p_s
ONE ROW PER MATCH
PATTERN (A+)
DEFINE A AS ts > 0
)
ORDER BY mn";
let ordinary = sql_plan(&ctx, one_row_sql).await?;
let source = match_recognize_node(&ordinary)
.expect("one-row matcher")
.bound_source()
.expect("bound source");
let native = 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 optimized_native = state.optimize(&native)?;
for (stage, plan) in [("direct", native), ("optimized", optimized_native)] {
let exported = to_substrait_plan_with_match_recognize(&plan, &state)?;
assert!(
!root_payload(&exported)?.summary_output_fields.is_empty(),
"one_row struct_default ({stage}): expected summary_output_fields"
);
let imported =
from_substrait_plan_with_match_recognize(&state, &exported).await?;
assert_eq!(
plan_rows(&ctx, imported).await?,
plan_rows(&ctx, plan).await?,
"one_row struct_default ({stage})"
);
}
Ok(())
}