use std::cell::Cell;
use relate_core::Result;
use crate::ctx::ExecCtx;
use crate::exec::pattern_policies::{MatchTail, Matched};
use crate::exec::pushdown::{MatchCap, Residual};
use crate::exec::rider::{PathProbe, Rider};
use crate::row::Row;
use crate::UsedSet;
pub(super) struct MatchedSink<'r, 'a> {
residual: &'r Residual<'r>,
kind: SinkKind<'r, 'a>,
halt: &'r Cell<bool>,
}
enum SinkKind<'r, 'a> {
Probe(&'a PathProbe<'a>),
Collect {
tail: MatchTail<'r>,
out: &'r mut Matched,
cap: Option<&'r mut MatchCap<'a>>,
},
Fold {
fold: &'r mut dyn FnMut(Row) -> Result<()>,
},
}
impl<'r, 'a> MatchedSink<'r, 'a> {
pub(super) fn new(
rider: Option<&'r mut Rider<'a, '_>>,
collect_halt: &'r Cell<bool>,
residual: &'r Residual<'r>,
tail: MatchTail<'r>,
out: &'r mut Matched,
) -> Self {
let (kind, halt) = match rider {
Some(Rider::Probe(probe)) => (SinkKind::Probe(probe), probe.halt),
Some(Rider::Cap(cap)) => (
SinkKind::Collect {
tail,
out,
cap: Some(&mut **cap),
},
collect_halt,
),
None => (
SinkKind::Collect {
tail,
out,
cap: None,
},
collect_halt,
),
};
Self {
residual,
kind,
halt,
}
}
pub(super) fn fold(
residual: &'r Residual<'r>,
halt: &'r Cell<bool>,
fold: &'r mut dyn FnMut(Row) -> Result<()>,
) -> Self {
Self {
residual,
kind: SinkKind::Fold { fold },
halt,
}
}
pub(super) fn residual(&self) -> &'r Residual<'r> {
self.residual
}
pub(super) fn halt_cell(&self) -> &'r Cell<bool> {
self.halt
}
pub(super) fn halted(&self) -> bool {
self.halt.get()
}
pub(super) fn offer(
&mut self,
ctx: ExecCtx<'_>,
row: Row,
used: impl FnOnce() -> UsedSet,
) -> Result<()> {
ctx.graph.cancel_tick()?;
let residual = self.residual;
match &mut self.kind {
SinkKind::Probe(probe) => {
probe.accept_row(ctx.graph, row, used(), residual, ctx.params)?;
}
SinkKind::Collect { tail, out, cap } => {
if let Some(row) = tail.finish_row(ctx.graph, row, cap.as_deref_mut())? {
tail.store_row(row, used, out);
}
if cap.as_ref().is_some_and(|cap| cap.full()) {
self.halt.set(true);
}
}
SinkKind::Fold { fold } => fold(row)?,
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use super::*;
use crate::ctx::ExecCtx;
use crate::exec::pushdown::Residual;
use crate::graph::Graph;
use crate::ExecGraph;
#[test]
fn a_cancelled_collect_offer_stops() {
let g = Graph::default();
let token = relate_core::CancelToken::new();
token.cancel();
let graph = ExecGraph::read(&g).with_cancel(Some(&token));
let params = BTreeMap::new();
let ctx = ExecCtx::new(&graph, ¶ms);
let residual = Residual::empty();
let halt = Cell::new(false);
let mut out: Matched = Vec::new();
let mut sink = MatchedSink::new(
None,
&halt,
&residual,
MatchTail::Finish { reduce: None },
&mut out,
);
let mut observed = None;
for _ in 0..2_048 {
if let Err(err) = sink.offer(ctx, Row::new(), UsedSet::default) {
observed = Some(err);
break;
}
}
let err = observed.expect("the collect arm must observe the cancelled statement");
assert!(
err.to_string().contains("query cancelled"),
"expected the cancellation error, got {err}"
);
}
}