use std::borrow::Cow;
use std::collections::BTreeMap;
use relate_core::{NodeId, Result, Value};
use relate_ir::{Clause, Expr, MatchMode, PathPattern, Projection};
use crate::ctx::ExecCtx;
use crate::metrics::WalkStart;
use crate::overlay::ExecGraph;
use crate::row::Row;
use super::super::graph_stats::GraphStats;
use super::super::match_folds::FoldCtx;
use super::super::pushdown::{flatten_and_owned, match_scope, Residual};
use super::matcher::{self, Chain, Contract};
use super::{counted_return, kernels_stood_down, record_walk_start, scan_segment};
pub(crate) struct CountEntry<'a> {
graph: &'a ExecGraph<'a>,
params: &'a BTreeMap<String, Value>,
entering: &'a Row,
pub(crate) item: &'a Projection,
conjuncts: Vec<Expr>,
compiled: Cow<'a, [PathPattern]>,
}
impl<'a> CountEntry<'a> {
pub(crate) fn open(ctx: &FoldCtx<'a>) -> Option<Self> {
let Some(Clause::Match {
optional: false,
match_mode: MatchMode::DifferentRelationships,
patterns,
where_clause,
search: None,
using_index: _,
using_join: _,
}) = ctx.clauses.first()
else {
return None;
};
let [entering] = ctx.rows else {
return None;
};
let [pattern] = patterns.as_slice() else {
return None;
};
if kernels_stood_down(ctx.graph.base()) {
return None;
}
let item = counted_return(ctx.clauses.get(1), pattern)?;
let conjuncts = where_clause
.as_ref()
.map(flatten_and_owned)
.unwrap_or_default();
Some(Self {
graph: ctx.graph,
params: ctx.params,
entering,
item,
conjuncts,
compiled: matcher::chain_spelling(patterns),
})
}
pub(crate) fn hop_count(&self) -> usize {
let [path] = &*self.compiled else {
unreachable!("CountEntry::open admits exactly one pattern")
};
path.rels.len()
}
pub(crate) fn chain(&self) -> Option<Box<Chain<'_>>> {
match matcher::compile(
&self.compiled,
MatchMode::DifferentRelationships,
self.entering,
&self.conjuncts,
) {
Some(Contract::Chain(chain)) => Some(chain),
_ => None,
}
}
pub(crate) fn conjuncts(&self) -> &[Expr] {
&self.conjuncts
}
pub(crate) fn stats(&self) -> GraphStats<'_> {
GraphStats::new(self.graph.base(), self.params)
}
pub(crate) fn scan(&self, chain: &Chain<'_>) -> Result<(ExecCtx<'a>, Vec<NodeId>)> {
#[cfg(test)]
super::kernel_engaged();
let ctx = ExecCtx::new(self.graph, self.params);
let residual = Residual {
conjuncts: &self.conjuncts,
scope: &match_scope(self.graph, self.entering, &self.compiled),
};
record_walk_start(WalkStart::seed_side_forward());
let starts = scan_segment(ctx, &chain.start, &residual)?;
Ok((ctx, starts))
}
}