use super::path::PathStep;
use crate::core::{AbsoluteRow, AfterMatchSkip, PhysicalRowCount, SymbolId};
use crate::execution::common::coordinates::absolute_row_to_usize;
use crate::nfa::CompiledAutomaton;
use datafusion_common::{DataFusionError, Result, internal_err};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct ResolvedInputColumn(usize);
impl ResolvedInputColumn {
pub(crate) const fn new_validated(index: usize) -> Self {
Self(index)
}
pub(crate) const fn index(self) -> usize {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct ResolvedBoolColumn(ResolvedInputColumn);
impl ResolvedBoolColumn {
pub(crate) const fn new_validated(index: usize) -> Self {
Self(ResolvedInputColumn::new_validated(index))
}
pub(crate) const fn index(self) -> usize {
self.0.index()
}
}
#[derive(Debug, Clone)]
pub(crate) struct SymbolColumn {
pub(crate) id: SymbolId,
pub(crate) column: ResolvedBoolColumn,
}
#[derive(Debug)]
pub(crate) struct SymbolTable {
pub(crate) columns: Vec<SymbolColumn>,
}
impl SymbolTable {
pub fn columns(&self) -> &[SymbolColumn] {
&self.columns
}
pub(crate) fn try_transition_live(
automaton: &CompiledAutomaton,
columns: &[SymbolColumn],
) -> Result<Self> {
let symbol_count = automaton.num_symbols();
let mut live = Vec::with_capacity(columns.len());
for column in columns {
let column_id = column.id;
if column_id.index() == 0 || column_id.index() >= symbol_count {
return internal_err!(
"MATCH_RECOGNIZE active symbol column ID {} is outside the compiled domain of {symbol_count} slots",
column_id.index()
);
}
let transition_live = (0..automaton.nfa().state_count()).any(|state_index| {
let state_id = automaton
.nfa()
.state_id(state_index)
.expect("scan index is inside the sealed state domain");
!automaton
.nfa()
.state(state_id)
.transitions(column_id)
.is_empty()
});
if transition_live {
live.push(column.clone());
}
}
Ok(Self { columns: live })
}
}
#[derive(Clone, Debug)]
pub(crate) enum ResolvedAfterMatchSkip {
PastLastRow,
ToNextRow,
ToFirst { symbol_id: SymbolId, name: String },
ToLast { symbol_id: SymbolId, name: String },
}
impl ResolvedAfterMatchSkip {
pub(crate) fn try_new(
clause: &AfterMatchSkip,
target: Option<SymbolId>,
) -> Result<Self> {
let resolved = match clause {
AfterMatchSkip::PastLastRow if target.is_none() => Some(Self::PastLastRow),
AfterMatchSkip::ToNextRow if target.is_none() => Some(Self::ToNextRow),
AfterMatchSkip::ToFirst(name) => target.map(|symbol_id| Self::ToFirst {
symbol_id,
name: name.clone(),
}),
AfterMatchSkip::ToLast(name) => target.map(|symbol_id| Self::ToLast {
symbol_id,
name: name.clone(),
}),
AfterMatchSkip::PastLastRow | AfterMatchSkip::ToNextRow => None,
};
resolved.ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE AFTER MATCH SKIP target is inconsistent".to_owned(),
)
})
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct NextMatchCursor {
pub(crate) row_idx: usize,
}
#[cfg(test)]
#[expect(
clippy::items_after_test_module,
reason = "cursor tests stay beside cursor planning"
)]
mod tests {
use super::NextMatchCursor;
use crate::core::{AbsoluteRow, SymbolId};
use crate::execution::matching::ResolvedAfterMatchSkip;
#[test]
fn selected_cursor_planning_checks_skip_targets_and_absolute_bounds() {
let start = AbsoluteRow::new(10);
let end = AbsoluteRow::new(13);
let symbol_target = AbsoluteRow::new(12);
let b = SymbolId::try_new(2, 3).unwrap();
for (skip, target, first, last, expected) in [
(ResolvedAfterMatchSkip::ToNextRow, None, start, end, Ok(11)),
(
ResolvedAfterMatchSkip::PastLastRow,
None,
start,
end,
Ok(14),
),
(
ResolvedAfterMatchSkip::ToFirst {
symbol_id: b,
name: "B".into(),
},
Some(symbol_target),
start,
end,
Ok(12),
),
(
ResolvedAfterMatchSkip::ToLast {
symbol_id: b,
name: "B".into(),
},
Some(symbol_target),
start,
end,
Ok(12),
),
(
ResolvedAfterMatchSkip::ToFirst {
symbol_id: b,
name: "B".into(),
},
Some(start),
start,
end,
Err("does not advance"),
),
(
ResolvedAfterMatchSkip::ToNextRow,
None,
AbsoluteRow::MAX,
AbsoluteRow::MAX,
Err("maximum absolute row number"),
),
(
ResolvedAfterMatchSkip::PastLastRow,
None,
start,
AbsoluteRow::MAX,
Err("maximum absolute row number"),
),
] {
let result = skip.plan_selected_cursor(first, last, false, target);
match expected {
Ok(row_idx) => assert_eq!(result.unwrap(), NextMatchCursor { row_idx }),
Err(message) => {
let error = result.unwrap_err();
assert!(error.to_string().contains(message), "{error}");
}
}
}
}
}
impl ResolvedAfterMatchSkip {
#[inline]
pub(crate) fn advance_row(best_end_row: AbsoluteRow) -> Result<usize> {
let next = best_end_row
.checked_add(PhysicalRowCount::new(1))
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE next scan row exceeds the maximum absolute row number"
.to_string(),
)
})?;
absolute_row_to_usize(next, "next scan row")
}
pub(crate) fn cursor_after(row: AbsoluteRow) -> Result<NextMatchCursor> {
Ok(NextMatchCursor {
row_idx: Self::advance_row(row)?,
})
}
#[inline]
pub(crate) fn observe_selected_step(
&self,
step: PathStep,
target: &mut Option<AbsoluteRow>,
) {
match self {
Self::ToFirst { symbol_id, .. }
if step.sym.to_index() == symbol_id.index() =>
{
*target = Some(target.map_or(step.row, |row| row.min(step.row)));
}
Self::ToLast { symbol_id, .. }
if step.sym.to_index() == symbol_id.index() =>
{
*target = Some(target.map_or(step.row, |row| row.max(step.row)));
}
_ => {}
}
}
pub(crate) fn plan_selected_cursor(
&self,
match_start_row: AbsoluteRow,
match_end_row: AbsoluteRow,
is_empty: bool,
symbol_target_row: Option<AbsoluteRow>,
) -> Result<NextMatchCursor> {
let mut cursor = Self::cursor_after(match_start_row)?;
if is_empty {
return Ok(cursor);
}
match self {
Self::PastLastRow => {
cursor = Self::cursor_after(match_end_row)?;
}
Self::ToNextRow => {}
Self::ToFirst { name, .. } | Self::ToLast { name, .. } => {
let target_label = match self {
Self::ToFirst { .. } => "FIRST",
Self::ToLast { .. } => "LAST",
Self::PastLastRow | Self::ToNextRow => unreachable!(),
};
let target_row = symbol_target_row.ok_or_else(|| {
DataFusionError::Execution(format!(
"AFTER MATCH SKIP TO {target_label} {name}: symbol not found in match"
))
})?;
if target_row <= match_start_row {
return datafusion_common::exec_err!(
"AFTER MATCH SKIP TO {} {}: skip target at row {} does not advance past the first row {} of the match",
target_label,
name,
target_row,
match_start_row
);
}
cursor.row_idx = absolute_row_to_usize(target_row, "symbol skip target")?;
}
}
Ok(cursor)
}
}