use crate::core::{
AbsoluteRow, AfterMatchSkip, MatchRecognizeOutputSpec, NavigationOffset, Pattern,
RowsPerMatch, Symbol,
};
use crate::planning::logical::{
ExecutableMatchProgramInput, LogicalMatchOutput, LogicalMatchProgramInput,
LogicalSymbolInput, MatchRecognize,
};
use crate::planning::{MatchCompilerOptions, SymbolRelationships, compile_match_program};
use datafusion::arrow::array::{Array, ArrayRef, BooleanArray, Int64Array, StringArray};
use datafusion::arrow::datatypes::{DataType, FieldRef, Metadata};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{Column, ScalarValue, TableReference};
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryConsumer, MemoryPool};
use datafusion::functions_aggregate::first_last::{first_value_udaf, last_value_udaf};
use datafusion::logical_expr::execution_props::ExecutionProps;
use datafusion::logical_expr::expr::{WindowFunction, WindowFunctionDefinition};
use datafusion::logical_expr::function::AccumulatorArgs;
use datafusion::logical_expr::{
Accumulator, AggregateUDF, AggregateUDFImpl, EmptyRelation, LogicalPlan, Signature,
Volatility, col, lit,
};
use datafusion::physical_expr::create_physical_expr;
use datafusion::physical_planner::DefaultPhysicalPlanner;
use datafusion::prelude::SessionContext;
use std::sync::LazyLock;
use crate::execution::matching::path::{PathNode, PathStep, Sym};
use crate::execution::storage::collection::BatchCollection;
use super::*;
fn compile_deferred_spec(
logical_field: Field,
predicate: Expr,
) -> Result<DeferredProgramSpec> {
compile_deferred_symbols(
logical_field,
Pattern::Symbol(Symbol::Named("A".into())),
vec![LogicalSymbolInput::deferred("A", predicate)],
)
}
fn compile_deferred_symbols(
logical_field: Field,
pattern: Pattern,
symbols: Vec<LogicalSymbolInput>,
) -> Result<DeferredProgramSpec> {
let input_schema = Arc::new(DFSchema::try_from(Schema::new(vec![logical_field]))?);
let input = LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema: Arc::clone(&input_schema),
});
let node = MatchRecognize::try_new(
input,
LogicalMatchProgramInput {
partition_by: vec![],
order_by: vec![],
after_skip: AfterMatchSkip::PastLastRow,
pattern,
symbols,
match_aware: ExecutableMatchProgramInput::new(vec![], vec![]),
output: LogicalMatchOutput::rows(
RowsPerMatch::OneRow,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
),
symbol_relationships: SymbolRelationships::default(),
},
)?;
let routed = compile_match_program(
node.program(),
input_schema.as_ref(),
MatchCompilerOptions::default(),
)?;
Ok(routed.deferred().expect("deferred program").clone())
}
fn eval_single_row(
factory: &DeferredEvaluatorFactory,
batch: RecordBatch,
) -> Result<bool> {
let schema = batch.schema();
let collection = BatchCollection::try_new(vec![batch], schema)?;
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(8 << 20));
let reservation = MemoryConsumer::new("compiler-test").register(&pool);
let mut history = factory.candidate_history(&reservation)?;
let nodes = [PathNode {
step: PathStep {
row: AbsoluteRow::new(0),
sym: Sym::from_index(1),
excluded: false,
},
prev: None,
depth: 0,
}];
history.begin(0, SymbolId::try_new(1, 2).unwrap(), 1)?;
loop {
if let Some(accepted) =
history.advance(&collection, &nodes, 0, 1, &mut |_| Ok(()))?
{
return Ok(accepted);
}
}
}
#[derive(Debug)]
struct PropagateNullabilityAccumulator(ScalarValue);
impl Accumulator for PropagateNullabilityAccumulator {
fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
let input = &values[0];
if !input.is_empty() {
self.0 = ScalarValue::try_from_array(input, input.len() - 1)?;
}
Ok(())
}
fn evaluate(&mut self) -> Result<ScalarValue> {
Ok(self.0.clone())
}
fn size(&self) -> usize {
size_of::<Self>()
}
fn state(&mut self) -> Result<Vec<ScalarValue>> {
Ok(vec![self.0.clone()])
}
fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
self.update_batch(states)
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct PropagateNullabilityAgg;
impl AggregateUDFImpl for PropagateNullabilityAgg {
fn name(&self) -> &str {
"propagate_nullability"
}
fn signature(&self) -> &Signature {
static SIGNATURE: LazyLock<Signature> =
LazyLock::new(|| Signature::any(1, Volatility::Immutable));
&SIGNATURE
}
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
Ok(arg_types[0].clone())
}
fn return_field(&self, arg_fields: &[FieldRef]) -> Result<FieldRef> {
Ok(Arc::new(
Field::new(
self.name(),
arg_fields[0].data_type().clone(),
arg_fields[0].is_nullable(),
)
.with_metadata(arg_fields[0].metadata().clone()),
))
}
fn accumulator(&self, acc_args: AccumulatorArgs<'_>) -> Result<Box<dyn Accumulator>> {
Ok(Box::new(PropagateNullabilityAccumulator(
ScalarValue::try_from(acc_args.return_field.data_type())?,
)))
}
}
#[test]
fn plan_operation_allows_physical_metadata_preservation_on_edge_aggregates() -> Result<()>
{
let planner = DefaultPhysicalPlanner::default();
let state = SessionContext::new().state();
let planning_ctx = PhysicalPlanningContext::default();
let symbols = [SymbolId::try_new(1, 2).unwrap()];
let symbol_names = [None, Some("A".to_owned())];
let physical_schema = Arc::new(Schema::new(vec![
Field::new("value", DataType::Int64, true)
.with_metadata(Metadata::new().with("source", "physical")),
]));
for udaf in [first_value_udaf(), last_value_udaf()] {
let predicate = Expr::WindowFunction(Box::new(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(udaf),
vec![col("value")],
)))
.eq(lit(42_i64));
let spec =
compile_deferred_spec(Field::new("value", DataType::Int64, true), predicate)?;
let factory = DeferredEvaluatorFactory::try_from_spec(
&spec,
&planner,
&state,
&planning_ctx,
&physical_schema,
&symbols,
&symbol_names,
)?;
let batch = RecordBatch::try_new(
Arc::clone(&physical_schema),
vec![Arc::new(Int64Array::from(vec![Some(42)]))],
)?;
assert!(eval_single_row(&factory, batch)?);
}
Ok(())
}
#[test]
fn plan_operation_allows_widened_nullability_and_rejects_narrowing() -> Result<()> {
let planner = DefaultPhysicalPlanner::default();
let state = SessionContext::new().state();
let planning_ctx = PhysicalPlanningContext::default();
let symbols = [SymbolId::try_new(1, 2).unwrap()];
let symbol_names = [None, Some("A".to_owned())];
let udaf = Arc::new(AggregateUDF::new_from_impl(PropagateNullabilityAgg));
let predicate = Expr::WindowFunction(Box::new(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(udaf),
vec![col("value")],
)))
.is_null();
let widened_spec = compile_deferred_spec(
Field::new("value", DataType::Int64, false),
predicate.clone(),
)?;
assert!(!widened_spec.operations()[0].result_field().is_nullable());
let widened_physical_schema = Arc::new(Schema::new(vec![
Field::new("value", DataType::Int64, true)
.with_metadata(Metadata::new().with("widened", "true")),
]));
let factory = DeferredEvaluatorFactory::try_from_spec(
&widened_spec,
&planner,
&state,
&planning_ctx,
&widened_physical_schema,
&symbols,
&symbol_names,
)?;
let null_batch = RecordBatch::try_new(
Arc::clone(&widened_physical_schema),
vec![Arc::new(Int64Array::from(vec![None]))],
)?;
assert!(eval_single_row(&factory, null_batch)?);
let narrowed_spec =
compile_deferred_spec(Field::new("value", DataType::Int64, true), predicate)?;
assert!(narrowed_spec.operations()[0].result_field().is_nullable());
let narrowed_physical_schema = Arc::new(Schema::new(vec![Field::new(
"value",
DataType::Int64,
false,
)]));
let err = DeferredEvaluatorFactory::try_from_spec(
&narrowed_spec,
&planner,
&state,
&planning_ctx,
&narrowed_physical_schema,
&symbols,
&symbol_names,
)
.expect_err("narrowing operation result nullability must fail");
assert!(
err.to_string()
.contains("Deferred operation 0 lowered to field"),
"{err}"
);
Ok(())
}
#[test]
fn qualified_duplicate_columns_rebase_by_position() -> Result<()> {
let field = Arc::new(Field::new("value", DataType::Int64, true));
let logical_schema = DFSchema::new_with_metadata(
["left", "right"]
.into_iter()
.map(|table| (Some(TableReference::bare(table)), Arc::clone(&field)))
.collect(),
Metadata::new(),
)?;
let expression = Expr::Column(Column::new(Some("left"), "value"))
.lt(Expr::Column(Column::new(Some("right"), "value")));
let physical = create_physical_expr(
&expression,
&logical_schema,
&ExecutionProps::new(),
&PhysicalPlanningContext::default(),
)?;
let target_schema = Arc::new(Schema::new(vec![Arc::clone(&field), field]));
let rebased = rebase_physical_expr(physical, &target_schema, &[Some(1), Some(0)])?;
let batch = RecordBatch::try_new(
target_schema,
vec![
Arc::new(Int64Array::from(vec![Some(20), Some(5), None])),
Arc::new(Int64Array::from(vec![Some(10), Some(10), Some(10)])),
],
)?;
let result = rebased.evaluate(&batch)?.into_array(batch.num_rows())?;
assert_eq!(
result.as_any().downcast_ref::<BooleanArray>().unwrap(),
&BooleanArray::from(vec![Some(true), Some(false), None])
);
Ok(())
}
#[test]
fn plan_history_rejects_missing_and_mismatched_physical_inputs() -> Result<()> {
let symbols = [SymbolId::try_new(1, 2).unwrap()];
let predicate = Expr::WindowFunction(Box::new(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(first_value_udaf()),
vec![col("value")],
)))
.is_not_null();
let spec =
compile_deferred_spec(Field::new("value", DataType::Int64, true), predicate)?;
for (schema, expected) in [
(Schema::empty(), "outside physical input schema"),
(
Schema::new(vec![Field::new("renamed", DataType::Int64, true)]),
"deferred history field value",
),
(
Schema::new(vec![Field::new("value", DataType::Int32, true)]),
"deferred history field value",
),
] {
let error = plan_history(&spec, &Arc::new(schema), &symbols)
.expect_err("physical history fields must match their logical owners");
assert!(error.to_string().contains(expected), "{error}");
}
Ok(())
}
#[test]
fn scalar_wrapped_aggregate_inputs_use_physical_nullability() -> Result<()> {
let planner = DefaultPhysicalPlanner::default();
let state = SessionContext::new().state();
let planning_ctx = PhysicalPlanningContext::default();
let propagate = Arc::new(AggregateUDF::new_from_impl(PropagateNullabilityAgg));
for (ty, argument, values) in [
(
DataType::Int64,
datafusion::functions::core::coalesce()
.call(vec![col("value"), col("value")]),
Arc::new(Int64Array::from(vec![None])) as ArrayRef,
),
(
DataType::Utf8,
datafusion::functions::string::lower().call(vec![col("value")]),
Arc::new(StringArray::from(vec![None::<&str>])) as ArrayRef,
),
] {
let predicate = Expr::WindowFunction(Box::new(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(Arc::clone(&propagate)),
vec![argument],
)))
.is_null();
let spec =
compile_deferred_spec(Field::new("value", ty.clone(), false), predicate)?;
assert!(!spec.operations()[0].result_field().is_nullable());
let physical_schema = Arc::new(Schema::new(vec![Field::new("value", ty, true)]));
let factory = DeferredEvaluatorFactory::try_from_spec(
&spec,
&planner,
&state,
&planning_ctx,
&physical_schema,
&[SymbolId::try_new(1, 2).unwrap()],
&[None, Some("A".into())],
)?;
assert!(
factory.program.operations[0]
.planned
.lowered
.aggregate
.field()
.is_nullable()
);
assert!(eval_single_row(
&factory,
RecordBatch::try_new(physical_schema, vec![values])?
)?);
}
Ok(())
}
#[test]
fn array_agg_lower_ignore_nulls_uses_widened_physical_field() -> Result<()> {
use datafusion::logical_expr::expr::NullTreatment;
let mut window = WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(
datafusion::functions_aggregate::array_agg::array_agg_udaf(),
),
vec![datafusion::functions::string::lower().call(vec![col("s")])],
);
window.params.null_treatment = Some(NullTreatment::IgnoreNulls);
let spec = compile_deferred_spec(
Field::new("s", DataType::Utf8, false),
Expr::WindowFunction(Box::new(window)).is_not_null(),
)?;
let physical_schema =
Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, true)]));
let factory = DeferredEvaluatorFactory::try_from_spec(
&spec,
&DefaultPhysicalPlanner::default(),
&SessionContext::new().state(),
&PhysicalPlanningContext::default(),
&physical_schema,
&[SymbolId::try_new(1, 2).unwrap()],
&[None, Some("A".into())],
)?;
let argument = &factory.program.operations[0].planned.input_exprs[0];
assert!(
argument
.return_field(&factory.program.history.schema)?
.is_nullable()
);
let batch = RecordBatch::try_new(
physical_schema,
vec![Arc::new(StringArray::from(vec![None, Some("ABC")]))],
)?;
let operation = &factory.program.operations[0].planned;
let mut accumulator = operation.lowered.aggregate.create_accumulator()?;
let inputs = operation
.input_exprs
.iter()
.map(|expr| expr.evaluate(&batch)?.into_array(batch.num_rows()))
.collect::<Result<Vec<_>>>()?;
accumulator.update_batch(&inputs)?;
let ScalarValue::List(result) = accumulator.evaluate()? else {
panic!("ARRAY_AGG must produce a list");
};
assert_eq!(
result
.values()
.as_any()
.downcast_ref::<StringArray>()
.unwrap(),
&StringArray::from(vec!["abc"])
);
Ok(())
}
#[test]
fn coalesce_preserves_physical_field_metadata_through_aggregate_lowering() -> Result<()> {
let physical_metadata = Metadata::new().with("source", "physical");
let physical_schema = Arc::new(Schema::new_with_metadata(
vec![
Field::new("value", DataType::Int64, true)
.with_metadata(physical_metadata.clone()),
],
Metadata::new().with("schema_source", "physical"),
));
let argument =
datafusion::functions::core::coalesce().call(vec![col("value"), col("value")]);
let predicate = Expr::WindowFunction(Box::new(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(first_value_udaf()),
vec![argument],
)))
.eq(lit(42_i64));
let spec = compile_deferred_spec(
Field::new("value", DataType::Int64, true)
.with_metadata(Metadata::new().with("source", "logical")),
predicate,
)?;
let factory = DeferredEvaluatorFactory::try_from_spec(
&spec,
&DefaultPhysicalPlanner::default(),
&SessionContext::new().state(),
&PhysicalPlanningContext::default(),
&physical_schema,
&[SymbolId::try_new(1, 2).unwrap()],
&[None, Some("A".into())],
)?;
let operation = &factory.program.operations[0].planned;
assert_eq!(
operation.input_exprs[0]
.return_field(&factory.program.history.schema)?
.metadata(),
&physical_metadata
);
assert_eq!(
operation.lowered.aggregate.field().metadata(),
&physical_metadata
);
assert_eq!(
factory.program.predicates[1]
.as_ref()
.unwrap()
.predicate_schema
.field(0)
.metadata(),
&physical_metadata
);
assert_eq!(
physical_backed_schema(spec.history_schema(), &factory.program.history.schema)?
.metadata(),
physical_schema.metadata()
);
assert!(eval_single_row(
&factory,
RecordBatch::try_new(
physical_schema,
vec![Arc::new(Int64Array::from(vec![42]))]
)?
)?);
Ok(())
}
#[test]
fn checking_a_does_not_evaluate_unreached_b_operations() -> Result<()> {
use crate::core::{RepetitionQuantifier, classifier_bits_col_name};
let array_agg = |argument| {
let mut window = WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(
datafusion::functions_aggregate::array_agg::array_agg_udaf(),
),
vec![argument],
);
window.params.filter = Some(Box::new(col(classifier_bits_col_name("A"))));
Expr::WindowFunction(Box::new(window))
};
for accept_a in [true, false] {
let a = array_agg(col("x"));
let b = Pattern::Symbol(Symbol::Named("B".into()));
let pattern = Pattern::Concat(vec![
Pattern::Symbol(Symbol::Named("A".into())),
if accept_a {
Pattern::Repetition(Box::new(b), RepetitionQuantifier::AtMostOne)
} else {
b
},
]);
let spec = compile_deferred_symbols(
Field::new("x", DataType::Int64, false),
pattern,
vec![
LogicalSymbolInput::deferred(
"A",
if accept_a {
a.is_not_null()
} else {
a.is_null()
},
),
LogicalSymbolInput::deferred(
"B",
array_agg(lit(1_i64) / col("x")).is_not_null(),
),
],
)?;
let physical_schema =
Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, false)]));
let factory = DeferredEvaluatorFactory::try_from_spec(
&spec,
&DefaultPhysicalPlanner::default(),
&SessionContext::new().state(),
&PhysicalPlanningContext::default(),
&physical_schema,
&[
SymbolId::try_new(1, 3).unwrap(),
SymbolId::try_new(2, 3).unwrap(),
],
&[None, Some("A".into()), Some("B".into())],
)?;
assert_eq!(
factory.program.predicates[1]
.as_ref()
.unwrap()
.operation_indices,
vec![0]
);
assert_eq!(
factory.program.predicates[2]
.as_ref()
.unwrap()
.operation_indices,
vec![1]
);
let values = if accept_a { vec![0] } else { vec![0, 2] };
assert_eq!(
eval_single_row(
&factory,
RecordBatch::try_new(
physical_schema,
vec![Arc::new(Int64Array::from(values))]
)?
)?,
accept_a
);
}
Ok(())
}
#[cfg(feature = "sql")]
#[tokio::test]
async fn sql_unreached_deferred_symbol_cannot_raise_divide_by_zero() -> Result<()> {
let ctx = crate::new_match_recognize_context(
datafusion::execution::SessionStateBuilder::new().with_default_features(),
)?;
for (pattern, values, a_test, expected_rows) in [
("A B?", "(0, 0)", "IS NOT NULL", 1),
("A B", "(0, 0), (1, 2)", "IS NULL", 0),
] {
let sql = format!(
"WITH t(ord, x) AS (VALUES {values}) SELECT ord FROM t
MATCH_RECOGNIZE (
ORDER BY ord
ALL ROWS PER MATCH
PATTERN ({pattern})
DEFINE A AS ARRAY_AGG(A.x) {a_test},
B AS ARRAY_AGG(1 / A.x) IS NOT NULL
)"
);
let batches = ctx.sql(&sql).await?.collect().await?;
assert_eq!(
batches.iter().map(RecordBatch::num_rows).sum::<usize>(),
expected_rows,
"{sql}"
);
}
Ok(())
}
#[test]
fn shared_operations_keep_symbol_local_accumulators_and_replay() -> Result<()> {
let sum = Expr::WindowFunction(Box::new(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(
datafusion::functions_aggregate::sum::sum_udaf(),
),
vec![col("x")],
)));
let count = Expr::WindowFunction(Box::new(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(
datafusion::functions_aggregate::count::count_udaf(),
),
vec![col("x")],
)));
let sequence = col(MatchMetadataColumn::MatchSequenceNumber.as_ref());
let pattern = Pattern::Concat(
["A", "B", "A"]
.into_iter()
.map(|name| Pattern::Symbol(Symbol::Named(name.into())))
.collect(),
);
let spec = compile_deferred_symbols(
Field::new("x", DataType::Int64, false),
pattern,
vec![
LogicalSymbolInput::deferred("A", sum.clone().eq(sequence.clone())),
LogicalSymbolInput::deferred(
"B",
sum.eq(sequence.clone()).and(count.eq(sequence)),
),
],
)?;
let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, false)]));
let symbols = [
SymbolId::try_new(1, 3).unwrap(),
SymbolId::try_new(2, 3).unwrap(),
];
let mut factory = DeferredEvaluatorFactory::try_from_spec(
&spec,
&DefaultPhysicalPlanner::default(),
&SessionContext::new().state(),
&PhysicalPlanningContext::default(),
&schema,
&symbols,
&[None, Some("A".into()), Some("B".into())],
)?;
assert_eq!(spec.operations().len(), 2);
assert_eq!(
spec.predicates()[0].as_ref().unwrap().operation_indices(),
&[0]
);
assert_eq!(
spec.predicates()[1].as_ref().unwrap().operation_indices(),
&[0, 1]
);
let collection = BatchCollection::try_new(
vec![RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(Int64Array::from(vec![1, 1, 1]))],
)?],
schema,
)?;
let nodes = [1, 2, 1, 1]
.into_iter()
.enumerate()
.map(|(index, symbol)| PathNode {
step: PathStep {
row: AbsoluteRow::new(index.min(2) as u64),
sym: Sym::from_index(symbol),
excluded: false,
},
prev: match index {
0 => None,
1 => Some(0),
_ => Some(1),
},
depth: index.min(2) as u32,
})
.collect::<Vec<_>>();
for save_inputs in [false, true] {
for predicate in Arc::get_mut(&mut factory.program)
.unwrap()
.predicates
.iter_mut()
.flatten()
{
predicate.save_history_inputs = save_inputs;
}
let memory = crate::execution::common::memory::new_unbounded_state_memory();
let mut history = factory.candidate_history(&memory)?;
for (node, symbol) in [
(0, symbols[0]),
(1, symbols[1]),
(2, symbols[0]),
(3, symbols[0]),
] {
history.begin(node, symbol, 1)?;
let accepted = loop {
if let Some(accepted) =
history.advance(&collection, &nodes, 0, 3, &mut |_| Ok(()))?
{
break accepted;
}
};
assert!(accepted, "node {node}, saved inputs {save_inputs}");
}
}
Ok(())
}
#[test]
fn symbol_lookahead_and_predicate_extras_are_narrow() -> Result<()> {
let sum = Expr::WindowFunction(Box::new(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(
datafusion::functions_aggregate::sum::sum_udaf(),
),
vec![col("x")],
)));
let next = Expr::WindowFunction(Box::new(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(crate::functions::udaf::mr_next_udaf()),
vec![
col("x"),
lit(1_u64),
lit(0_i64),
col(MatchMetadataColumn::Classifier.as_ref()).is_not_null(),
crate::planning::logical::valid_match_row_expr(),
],
)));
let spec = compile_deferred_symbols(
Field::new("x", DataType::Int64, false),
Pattern::Concat(
["A", "B"]
.into_iter()
.map(|name| Pattern::Symbol(Symbol::Named(name.into())))
.collect(),
),
vec![
LogicalSymbolInput::deferred("A", sum.eq(col("x"))),
LogicalSymbolInput::deferred(
"B",
next.is_not_null()
.and(col(MatchMetadataColumn::MatchNumber.as_ref()).eq(lit(1_i64))),
),
],
)?;
assert_eq!(spec.max_lookahead_rows(), NavigationOffset::ONE);
let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, false)]));
let factory = DeferredEvaluatorFactory::try_from_spec(
&spec,
&DefaultPhysicalPlanner::default(),
&SessionContext::new().state(),
&PhysicalPlanningContext::default(),
&schema,
&[
SymbolId::try_new(1, 3).unwrap(),
SymbolId::try_new(2, 3).unwrap(),
],
&[None, Some("A".into()), Some("B".into())],
)?;
for (symbol, lookahead, extra) in [
(1, NavigationOffset::ZERO, "x"),
(
2,
NavigationOffset::ONE,
MatchMetadataColumn::MatchNumber.as_ref(),
),
] {
let predicate = factory.program.predicates[symbol].as_ref().unwrap();
assert_eq!(predicate.max_lookahead_rows, lookahead);
assert_eq!(predicate.predicate_schema.fields().len(), 2);
assert_eq!(predicate.extra_ordinals.len(), 1);
assert_eq!(
factory
.program
.history
.schema
.field(predicate.extra_ordinals[0])
.name(),
extra
);
}
let collection = BatchCollection::try_new(
vec![RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(Int64Array::from(vec![1, 99]))],
)?],
schema,
)?;
let memory = crate::execution::common::memory::new_unbounded_state_memory();
let mut history = factory.candidate_history(&memory)?;
let nodes = [PathNode {
step: PathStep {
row: AbsoluteRow::new(0),
sym: Sym::from_index(1),
excluded: false,
},
prev: None,
depth: 0,
}];
history.begin(0, SymbolId::try_new(1, 3).unwrap(), 1)?;
loop {
if let Some(accepted) =
history.advance(&collection, &nodes, 0, 2, &mut |_| Ok(()))?
{
assert!(accepted);
break;
}
}
assert_eq!(
history.gathered_rows(),
1,
"A must not gather B's lookahead"
);
Ok(())
}