use super::*;
#[tokio::test]
async fn ordinary_substring_export_uses_datafusion_function_binding() -> Result<()> {
use datafusion::common::ScalarValue;
let ctx = SessionContext::new();
let plan = sql_plan(
&ctx,
"SELECT SUBSTRING(x FROM 2 FOR 1) AS result FROM (VALUES ('abc')) AS t(x)",
)
.await?;
let state = ctx.state();
let exported = to_substrait_plan_with_match_recognize(&plan, &state)?;
assert!(exported.expected_type_urls.is_empty());
let imported = datafusion_substrait::logical_plan::consumer::from_substrait_plan(
&state, &exported,
)
.await?;
let nullable = plan.schema().field(0).is_nullable();
assert_output(
&ctx,
imported,
&[("result", DataType::Utf8, nullable)],
&[vec![ScalarValue::Utf8(Some("b".into()))]],
)
.await
}
#[tokio::test]
async fn subquery_matcher_preserves_substring_binding() -> Result<()> {
let ctx = context_with_input().await?;
let plan = sql_plan(
&ctx,
r#"
SELECT SUBSTRING('abc' FROM 2 FOR 1) AS result,
(SELECT first_company FROM t MATCH_RECOGNIZE (
ORDER BY ts
MEASURES FIRST(A.company) AS first_company
ONE ROW PER MATCH PATTERN (A) DEFINE A AS TRUE
) LIMIT 1) AS selected_company
"#,
)
.await?;
let exported = to_substrait_plan_with_match_recognize(&plan, &ctx.state())?;
assert_eq!(exported.expected_type_urls, [MATCH_RECOGNIZE_TYPE_URL]);
let extensions = Extensions::try_from(&exported.extensions)?;
assert!(
extensions
.functions
.values()
.any(|name| name == BUILTIN_SUBSTRING_NAME)
);
Ok(())
}
#[tokio::test]
async fn substring_syntax_preserves_builtin_binding_across_roundtrip() -> Result<()> {
use datafusion::common::ScalarValue;
use datafusion::logical_expr::{ColumnarValue, Volatility, create_udf};
let ctx = context_with_input().await?;
for (name, result) in [("substr", "custom"), ("Substr", "mixed case")] {
ctx.register_udf(create_udf(
name,
vec![DataType::Utf8, DataType::Int64, DataType::Int64],
DataType::Utf8,
Volatility::Immutable,
Arc::new(move |_| {
Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some(
result.into(),
))))
}),
));
}
let plan = sql_plan(
&ctx,
r#"
SELECT SUBSTRING(company FROM 2 FOR 1) AS ordinary_sql,
input_measure, pattern_measure, registered,
"Substr"(company, 2, 1) AS registered_mixed_case
FROM t MATCH_RECOGNIZE (
PARTITION BY company ORDER BY ts
MEASURES SUBSTRING(company FROM 2 FOR 1) AS input_measure,
SUBSTRING(A.company FROM 2 FOR 1) AS pattern_measure,
"substr"(A.company, 2, 1) AS registered
ONE ROW PER MATCH
PATTERN (A)
DEFINE A AS ts = 1
)
"#,
)
.await?;
assert_roundtrip_output(
&ctx,
plan,
&[
("ordinary_sql", DataType::Utf8, true),
("input_measure", DataType::Utf8, true),
("pattern_measure", DataType::Utf8, true),
("registered", DataType::Utf8, true),
("registered_mixed_case", DataType::Utf8, true),
],
&[["c", "c", "c", "custom", "mixed case"]
.into_iter()
.map(|value| ScalarValue::Utf8(Some(value.into())))
.collect()],
)
.await
}
#[tokio::test]
async fn correlated_subqueries_roundtrip_over_match_output() -> Result<()> {
use datafusion::common::ScalarValue::Int64;
let ctx = context_with_input().await?;
ctx.register_batch(
"lookups",
RecordBatch::try_from_iter([
("ts", Arc::new(Int64Array::from(vec![1, 2, 3])) as ArrayRef),
(
"value",
Arc::new(Int64Array::from(vec![11, 22, 33])) as ArrayRef,
),
])?,
)?;
for (projection, values) in [
(
"(SELECT MAX(o.value) FROM lookups o WHERE o.ts = m.ts)",
[11, 22, 33],
),
(
"(SELECT MAX(o.value) FROM lookups o WHERE o.ts = m.ts)
+ (SELECT MIN(o.value) FROM lookups o WHERE o.ts = m.ts)",
[22, 44, 66],
),
] {
let plan = sql_plan(
&ctx,
&format!(
"WITH m AS (SELECT ts FROM t MATCH_RECOGNIZE (
ORDER BY ts ALL ROWS PER MATCH PATTERN (A+) DEFINE A AS TRUE))
SELECT m.ts, {projection} AS matched_id FROM m ORDER BY m.ts"
),
)
.await?;
assert_roundtrip_output(
&ctx,
plan,
&[
("ts", DataType::Int64, true),
("matched_id", DataType::Int64, true),
],
&[
vec![Int64(Some(1)), Int64(Some(values[0]))],
vec![Int64(Some(2)), Int64(Some(values[1]))],
vec![Int64(Some(3)), Int64(Some(values[2]))],
],
)
.await?;
}
Ok(())
}
#[tokio::test]
async fn nested_lambdas_roundtrip_in_matcher_input_views() -> Result<()> {
let ctx = context_with_input().await?;
ctx.sql("SET datafusion.sql_parser.dialect = 'databricks'")
.await?
.collect()
.await?;
ctx.sql(
"CREATE VIEW lambda_input AS SELECT ts,
array_transform([price], x -> array_transform([1,2], y -> x+y+ts)) AS nested,
array_transform([ts], x -> x+1) AS shifted FROM t",
)
.await?
.collect()
.await?;
let expected = sql_plan(
&ctx,
"SELECT * FROM (VALUES (1, [[12,13]], [2]),
(2, [[15,16]], [3]), (3, [[18,19]], [4])) AS e(ts,nested,shifted)",
)
.await?;
ctx.sql("SET datafusion.sql_parser.dialect = 'generic'")
.await?
.collect()
.await?;
let plan = sql_plan(
&ctx,
"SELECT ts, nested, shifted FROM lambda_input MATCH_RECOGNIZE (
ORDER BY ts ALL ROWS PER MATCH PATTERN (A+) DEFINE A AS TRUE) ORDER BY ts",
)
.await?;
let plan = ctx.state().optimize(&plan)?;
assert!(match_recognize_node(&plan).is_some());
assert!(
plan.display_indent()
.to_string()
.contains("array_transform")
);
let expected_rows = plan_rows(&ctx, expected).await?;
assert_eq!(plan_rows(&ctx, plan.clone()).await?, expected_rows);
assert_eq!(roundtrip_rows(&ctx, &plan).await?, expected_rows);
Ok(())
}
#[tokio::test]
async fn exported_detail_decodes_and_roundtrips_execution() -> Result<()> {
let ctx = context_with_input().await?;
let imported = from_substrait_plan_with_match_recognize(
&ctx.state(),
&plan_for_payload(base_payload()),
)
.await?;
let exported = to_substrait_plan_with_match_recognize(&imported, &ctx.state())?;
let payload = root_payload(&exported)?;
assert_eq!(
exported.expected_type_urls,
[MATCH_RECOGNIZE_TYPE_URL.to_owned()]
);
assert_eq!(payload.schema_version, Some(0));
assert!(payload.semantic_node && payload.semantic_node_finalizes_one_row);
assert_eq!(
payload
.required_features
.iter()
.map(String::as_str)
.collect::<BTreeSet<_>>(),
BTreeSet::from([
MATCH_RECOGNIZE_EXTENSION_FEATURE,
DATAFUSION_WINDOW_MODIFIERS_FEATURE,
MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE,
DATAFUSION_SEMANTIC_ONE_ROW_FEATURE,
])
);
assert_roundtrip_output(
&ctx,
imported,
&[
("company", DataType::Utf8, true),
("last_price", DataType::Int64, true),
],
&[vec!["acme".into(), 14_i64.into()]],
)
.await
}
#[tokio::test]
async fn reluctant_quantifiers_roundtrip_sql_execution() -> Result<()> {
let ctx = context_with_input().await?;
for (pattern, reluctant, groups) in [
("A+? B", true, vec![(1_i64, 1_i64, "A"), (2, 1, "B")]),
(
"(A+?)? B",
true,
vec![(1_i64, 1_i64, "A"), (2, 1, "B"), (3, 2, "B")],
),
(
"(A+)? B",
false,
vec![(1_i64, 1_i64, "A"), (2, 1, "A"), (3, 1, "B")],
),
] {
let sql = format!(
"SELECT company, ts, price, mn, cls FROM t MATCH_RECOGNIZE (
PARTITION BY company ORDER BY ts
MEASURES MATCH_NUMBER() AS mn, CLASSIFIER() AS cls
ALL ROWS PER MATCH OMIT EMPTY MATCHES
PATTERN ({pattern}) DEFINE A AS true, B AS true)
ORDER BY company, ts, mn"
);
let direct = ctx.sql(&sql).await?.logical_plan().clone();
let exported = to_substrait_plan_with_match_recognize(&direct, &ctx.state())?;
let payload = root_payload(&exported)?;
assert_eq!(
payload
.required_features
.iter()
.any(|feature| feature == MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE),
reluctant,
"{pattern}"
);
let rows = groups
.into_iter()
.map(|(ts, number, classifier)| {
vec![
"acme".into(),
ts.into(),
(8 + 2 * ts).into(),
number.into(),
classifier.into(),
]
})
.collect::<Vec<_>>();
assert_roundtrip_output(
&ctx,
direct,
&[
("company", DataType::Utf8, true),
("ts", DataType::Int64, true),
("price", DataType::Int64, true),
("mn", DataType::Int64, true),
("cls", DataType::Utf8, true),
],
&rows,
)
.await?;
}
Ok(())
}
#[tokio::test]
async fn internal_possessive_promotion_preserves_source_roundtrip() -> Result<()> {
let ctx = context_with_input().await?;
let direct = sql_plan(
&ctx,
"SELECT company, n FROM t MATCH_RECOGNIZE (
PARTITION BY company ORDER BY ts MEASURES COUNT(*) AS n
PATTERN (A* B) DEFINE A AS price < 12, B AS price >= 12)
ORDER BY company, n",
)
.await?;
let exported = to_substrait_plan_with_match_recognize(&direct, &ctx.state())?;
assert_eq!(
decode::decode_pattern(root_payload(&exported)?.pattern)?,
Pattern::Concat(vec![
Pattern::Repetition(
Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
crate::core::RepetitionQuantifier::ZeroOrMore,
),
Pattern::Symbol(Symbol::Named("B".into())),
]),
"export retains the caller's source pattern before internal promotion"
);
let imported =
from_substrait_plan_with_match_recognize(&ctx.state(), &exported).await?;
for plan in [direct, imported] {
let physical = ctx
.execute_logical_plan(plan.clone())
.await?
.create_physical_plan()
.await?;
let display = datafusion::physical_plan::displayable(physical.as_ref())
.indent(false)
.to_string();
assert!(display.contains("pattern=[A*+ B]"), "{display}");
assert_output(
&ctx,
plan,
&[
("company", DataType::Utf8, true),
("n", DataType::Int64, false),
],
&[
vec!["acme".into(), 1_i64.into()],
vec!["acme".into(), 2_i64.into()],
],
)
.await?;
}
Ok(())
}
#[tokio::test]
async fn computed_partition_keys_roundtrip_without_exposing_preparation() -> Result<()> {
let ctx = context_with_input().await?;
use datafusion::logical_expr::{Volatility, create_udf};
ctx.register_udf(create_udf(
"volatile_key",
vec![DataType::Int64],
DataType::Int64,
Volatility::Volatile,
Arc::new(|args| Ok(args[0].clone())),
));
for (case, sql, columns, rows) in [
(
"one row fallback",
"SELECT * FROM t MATCH_RECOGNIZE (
PARTITION BY upper(company) ORDER BY ts
MEASURES FIRST(abs(A.price)) AS first_price, LAST(B.price) AS last_price,
COUNT(*) AS n
ONE ROW PER MATCH PATTERN (A+ B)
DEFINE A AS price < 14, B AS price >= 14)",
vec![
("upper(t.company)", DataType::Utf8, true),
("first_price", DataType::Int64, true),
("last_price", DataType::Int64, true),
("n", DataType::Int64, false),
],
vec![vec![
"ACME".into(),
10_i64.into(),
14_i64.into(),
3_i64.into(),
]],
),
(
"selected endpoints over a signed-zero partition",
"SELECT first_price,last_price FROM t MATCH_RECOGNIZE (
PARTITION BY CASE WHEN ts = 1 THEN CAST('-0' AS DOUBLE)
ELSE CAST('0' AS DOUBLE) END ORDER BY ts
MEASURES FIRST(A.price) AS first_price,LAST(B.price) AS last_price
ONE ROW PER MATCH PATTERN (A+ B)
DEFINE A AS price < 14,B AS price >= 14)",
vec![
("first_price", DataType::Int64, true),
("last_price", DataType::Int64, true),
],
vec![vec![10_i64.into(), 14_i64.into()]],
),
(
"signed-zero partition with input navigation",
"SELECT n FROM t MATCH_RECOGNIZE (
PARTITION BY CASE WHEN ts = 1 THEN CAST('-0' AS DOUBLE) ELSE CAST('0' AS DOUBLE) END
ORDER BY ts MEASURES COUNT(*) AS n ONE ROW PER MATCH
PATTERN (A B+) DEFINE A AS TRUE, B AS ts = PREV(ts) + 1)",
vec![("n", DataType::Int64, false)],
vec![vec![3_i64.into()]],
),
(
"all rows column order",
"SELECT * FROM t MATCH_RECOGNIZE (
PARTITION BY upper(company) ORDER BY ts
MEASURES MATCH_NUMBER() AS mn ALL ROWS PER MATCH
PATTERN (A+) DEFINE A AS true) ORDER BY ts",
vec![
("company", DataType::Utf8, true),
("ts", DataType::Int64, true),
("mn", DataType::Int64, true),
("price", DataType::Int64, true),
],
vec![
vec!["acme".into(), 1_i64.into(), 1_i64.into(), 10_i64.into()],
vec!["acme".into(), 2_i64.into(), 1_i64.into(), 12_i64.into()],
vec!["acme".into(), 3_i64.into(), 1_i64.into(), 14_i64.into()],
],
),
(
"nullable pattern without terminal empty match",
"SELECT * FROM t MATCH_RECOGNIZE (
PARTITION BY upper(company) ORDER BY ts
MEASURES COUNT(*) AS n ONE ROW PER MATCH
PATTERN (A*) DEFINE A AS price > 0) ORDER BY n",
vec![
("upper(t.company)", DataType::Utf8, true),
("n", DataType::Int64, false),
],
vec![vec!["ACME".into(), 3_i64.into()]],
),
(
"volatile keys with a partition input window",
"WITH matches(bucket, n) AS (
SELECT * FROM t MATCH_RECOGNIZE (
PARTITION BY volatile_key(ts % 2) ORDER BY volatile_key(ts)
MEASURES COUNT(*) AS n ONE ROW PER MATCH
PATTERN (A*) DEFINE A AS PREV(ts, 1, -1) < ts)
)
SELECT bucket, n FROM matches ORDER BY bucket, n",
vec![
("bucket", DataType::Int64, true),
("n", DataType::Int64, false),
],
vec![
vec![0_i64.into(), 1_i64.into()],
vec![1_i64.into(), 2_i64.into()],
],
),
(
"match-aware define",
"SELECT * FROM t MATCH_RECOGNIZE (
PARTITION BY upper(company) ORDER BY ts
MEASURES COUNT(*) AS n ONE ROW PER MATCH
PATTERN (A+)
DEFINE A AS upper(company) = 'ACME' AND COUNT(A.*) <= 2
AND (PREV(ts) IS NULL OR PREV(ts) < ts)) ORDER BY n",
vec![
("upper(t.company)", DataType::Utf8, true),
("n", DataType::Int64, false),
],
vec![
vec!["ACME".into(), 1_i64.into()],
vec!["ACME".into(), 2_i64.into()],
],
),
] {
let direct = sql_plan(&ctx, sql).await?;
if case == "one row fallback" {
assert!(
!match_recognize_node(&direct)
.unwrap()
.program()
.output()
.finalizes_selected_summaries()
);
}
if case == "match-aware define" {
assert!(
match_recognize_node(&direct)
.unwrap()
.program()
.requires_match_aware_defines()
);
}
let optimized = ctx.state().optimize(&direct)?;
for plan in [direct, optimized] {
assert_roundtrip_output(&ctx, plan, &columns, &rows).await?;
}
}
Ok(())
}
#[tokio::test]
async fn repeated_volatile_keys_keep_independent_ordering() -> Result<()> {
use datafusion::common::cast::as_int64_array;
use datafusion::logical_expr::{ColumnarValue, Volatility, create_udf};
use std::sync::atomic::{AtomicUsize, Ordering};
let ctx = context_with_input().await?;
let calls = Arc::new(AtomicUsize::new(0));
let udf_calls = Arc::clone(&calls);
ctx.register_udf(create_udf(
"alternating_key",
vec![DataType::Int64],
DataType::Int64,
Volatility::Volatile,
Arc::new(move |args| {
let ColumnarValue::Array(array) = &args[0] else {
return datafusion::common::exec_err!("expected the input ts array");
};
let bucket_call = udf_calls.fetch_add(1, Ordering::Relaxed).is_multiple_of(2);
let keys = as_int64_array(array)?
.iter()
.map(|value| {
value.map(|value| if bucket_call { value % 2 } else { -value })
})
.collect::<Int64Array>();
Ok(ColumnarValue::Array(Arc::new(keys)))
}),
));
let columns = [
("bucket", DataType::Int64, true),
("first_ts", DataType::Int64, true),
];
let rows = [
vec![0_i64.into(), 2_i64.into()],
vec![1_i64.into(), 3_i64.into()],
];
for (input, partition, order, roundtrip) in [
(
"SELECT ts FROM t",
"alternating_key(ts)",
"alternating_key(ts)",
true,
),
(
"SELECT ts FROM t",
"alternating_key(ts)",
"alternating_key(ts) * 1",
false,
),
(
"SELECT ts, alternating_key(ts) AS p FROM t",
"p",
"alternating_key(ts)",
false,
),
] {
let sql = format!(
"WITH source AS ({input}), matches(bucket, first_ts) AS (
SELECT * FROM source MATCH_RECOGNIZE (
PARTITION BY {partition} ORDER BY {order}, ts
MEASURES FIRST(ts) AS first_ts ONE ROW PER MATCH
PATTERN (A+) DEFINE A AS TRUE)
)
SELECT bucket, first_ts FROM matches ORDER BY bucket"
);
calls.store(0, Ordering::Relaxed);
let plan = sql_plan(&ctx, &sql).await?;
if roundtrip {
assert_roundtrip_output(&ctx, plan, &columns, &rows).await?;
assert_eq!(calls.load(Ordering::Relaxed), 4);
} else {
assert_output(&ctx, plan, &columns, &rows).await?;
assert_eq!(calls.load(Ordering::Relaxed), 2);
}
}
Ok(())
}
#[tokio::test]
async fn partition_key_measures_roundtrip_with_preserved_nullability() -> Result<()> {
let ctx = context_with_input().await?;
ctx.register_batch(
"partition_key_edges",
RecordBatch::try_new(
Arc::new(Schema::new(vec![
Field::new("required_key", DataType::Int64, false),
Field::new("nullable_key", DataType::Int64, true),
Field::new("ord", DataType::Int64, false),
])),
vec![
Arc::new(Int64Array::from(vec![1, 1, 2, 2])),
Arc::new(Int64Array::from(vec![None, None, Some(20), Some(20)])),
Arc::new(Int64Array::from(vec![1, 2, 1, 2])),
],
)?,
)?;
let direct = sql_plan(
&ctx,
"SELECT first_key, last_key, first_nullable, last_nullable, n, nullable_n
FROM partition_key_edges MATCH_RECOGNIZE (
PARTITION BY required_key, nullable_key ORDER BY ord
MEASURES FIRST(required_key) AS first_key, LAST(required_key) AS last_key,
FIRST(nullable_key) AS first_nullable, LAST(nullable_key) AS last_nullable,
COUNT(A.required_key) AS n, COUNT(A.nullable_key) AS nullable_n
ONE ROW PER MATCH PATTERN (A+) DEFINE A AS true)
ORDER BY first_key",
)
.await?;
assert!(
match_recognize_node(&direct)
.unwrap()
.program()
.output()
.finalizes_selected_summaries()
);
let columns = [
("first_key", DataType::Int64, true),
("last_key", DataType::Int64, true),
("first_nullable", DataType::Int64, true),
("last_nullable", DataType::Int64, true),
("n", DataType::Int64, false),
("nullable_n", DataType::Int64, false),
];
let null = datafusion::common::ScalarValue::Int64(None);
let rows = [
vec![
1_i64.into(),
1_i64.into(),
null.clone(),
null,
2_i64.into(),
0_i64.into(),
],
vec![
2_i64.into(),
2_i64.into(),
20_i64.into(),
20_i64.into(),
2_i64.into(),
2_i64.into(),
],
];
let optimized = ctx.state().optimize(&direct)?;
for plan in [direct, optimized] {
assert_roundtrip_output(&ctx, plan, &columns, &rows).await?;
}
Ok(())
}
#[tokio::test]
async fn required_list_children_roundtrip_matcher_passthrough() -> Result<()> {
let ctx = required_list_input_context().await?;
let plan = sql_plan(
&ctx,
"SELECT id, payload FROM list_payload_input MATCH_RECOGNIZE (
ORDER BY id ALL ROWS PER MATCH PATTERN (A+) DEFINE A AS true
) ORDER BY id",
)
.await?;
let node = match_recognize_node(&plan).expect("matcher passthrough");
assert_eq!(
node.schema()
.field_with_unqualified_name("payload")?
.data_type(),
&DataType::List(Arc::new(Field::new("item", DataType::Int64, false))),
);
use datafusion::common::ScalarValue;
let columns = [
("id", DataType::Int64, true),
(
"payload",
DataType::List(Arc::new(Field::new("item", DataType::Int64, false))),
true,
),
];
let expected = [
vec![
1_i64.into(),
ScalarValue::List(ScalarValue::new_list(
&[10_i64.into(), 20_i64.into()],
&DataType::Int64,
false,
)),
],
vec![
2_i64.into(),
ScalarValue::List(ScalarValue::new_list(
&[30_i64.into()],
&DataType::Int64,
false,
)),
],
];
assert_roundtrip_output(&ctx, plan, &columns, &expected).await
}
#[tokio::test]
async fn required_list_children_roundtrip_generated_match_summaries() -> Result<()> {
let ctx = required_list_input_context().await?;
let plan = sql_plan(
&ctx,
"SELECT first_payload, last_payload FROM list_payload_input MATCH_RECOGNIZE (
ORDER BY id MEASURES FIRST(A.payload) AS first_payload,
LAST(A.payload) AS last_payload
ONE ROW PER MATCH PATTERN (A+) DEFINE A AS true
)",
)
.await?;
use datafusion::common::ScalarValue;
let list_type = DataType::List(Arc::new(Field::new("item", DataType::Int64, false)));
let columns = [
("first_payload", list_type.clone(), true),
("last_payload", list_type, true),
];
let expected = [vec![
ScalarValue::List(ScalarValue::new_list(
&[10_i64.into(), 20_i64.into()],
&DataType::Int64,
false,
)),
ScalarValue::List(ScalarValue::new_list(
&[30_i64.into()],
&DataType::Int64,
false,
)),
]];
assert_roundtrip_output(&ctx, plan, &columns, &expected).await
}