use std::collections::{BTreeMap, HashSet};
use relate_core::{NodeId, Result, Value};
use relate_ir::{BinaryOp, DisjunctionArms, Expr, NodePattern};
use relate_names::SmallName;
use crate::eval::expr_vars;
use crate::overlay::{intersect_ids, union_ids, ExecGraph};
use crate::pattern_walk::PatternMapRole;
use crate::pattern_walk::{binding, pattern_props, Binding, NodeBinding};
use crate::row::Row;
use crate::tiered_set::{TieredWordSet, WordHash};
mod seek;
#[cfg(test)]
mod tests;
pub(crate) use seek::{id_fn_conversion, leaf_seek, IdConversion, Seek, ServedIds};
pub(crate) fn label_index_seekable(node: &NodePattern) -> bool {
node.label_expr
.as_ref()
.is_none_or(|expr| expr.is_static_conjunction())
}
pub(crate) fn scan_answers_exactly(node: &NodePattern) -> bool {
label_index_seekable(node) || node.static_disjunction_arms().is_some()
}
fn seek_union(
graph: &ExecGraph<'_>,
seek: &Seek,
arms: &DisjunctionArms<'_>,
) -> Result<Option<Vec<NodeId>>> {
let mut served: Vec<Vec<NodeId>> = Vec::with_capacity(arms.len());
for arm in arms.arms() {
let labels: Vec<String> = arm.map(|label| label.to_string()).collect();
if !seek.servable(graph, &labels, true) {
return Ok(None);
}
let Some(ids) = seek.serve(graph, &labels) else {
return Ok(None);
};
served.push(ids.into_ids());
}
union_dedup(served.into_iter()).map(Some)
}
fn union_dedup(served: impl Iterator<Item = Vec<NodeId>>) -> Result<Vec<NodeId>> {
let mut seen = TieredWordSet::new(WordHash::Id);
let mut ids = Vec::new();
for arm_ids in served {
for id in arm_ids {
if seen.insert(id as u64)? {
ids.push(id);
}
}
}
ids.sort_unstable();
Ok(ids)
}
enum IndexArm {
Served(ServedIds),
Unserved,
Decline,
}
struct OrCtx<'a> {
graph: &'a ExecGraph<'a>,
row: &'a Row,
params: &'a BTreeMap<String, Value>,
cypher_version: Option<u32>,
labels: &'a [String],
label_seekable: bool,
}
fn or_union_candidates(var: &SmallName, conjuncts: &[Expr], ctx: &OrCtx<'_>) -> Option<ServedIds> {
conjuncts
.iter()
.filter(|c| {
matches!(
c,
Expr::Binary {
op: BinaryOp::Or,
..
}
)
})
.filter_map(|c| match index_arm(var, c, ctx) {
IndexArm::Served(served) => Some(served),
IndexArm::Unserved | IndexArm::Decline => None,
})
.reduce(|previous, served| previous.folded(served, intersect_ids))
}
fn index_arm(var: &SmallName, expr: &Expr, ctx: &OrCtx<'_>) -> IndexArm {
match expr {
Expr::Binary {
op: BinaryOp::Or,
left,
right,
} => match (index_arm(var, left, ctx), index_arm(var, right, ctx)) {
(IndexArm::Decline, _) | (_, IndexArm::Decline) => IndexArm::Decline,
(IndexArm::Served(a), IndexArm::Served(b)) => IndexArm::Served(a.folded(b, union_ids)),
_ => IndexArm::Unserved,
},
Expr::Binary {
op: BinaryOp::And,
left,
right,
} => match (index_arm(var, left, ctx), index_arm(var, right, ctx)) {
(IndexArm::Decline, _) | (_, IndexArm::Decline) => IndexArm::Decline,
(IndexArm::Served(a), IndexArm::Served(b)) => {
IndexArm::Served(a.folded(b, intersect_ids))
}
(IndexArm::Served(a), IndexArm::Unserved)
| (IndexArm::Unserved, IndexArm::Served(a)) => {
IndexArm::Served(ServedIds::Superset(a.into_ids()))
}
(IndexArm::Unserved, IndexArm::Unserved) => IndexArm::Unserved,
},
other => index_leaf(var, other, ctx),
}
}
fn index_leaf(var: &SmallName, expr: &Expr, ctx: &OrCtx<'_>) -> IndexArm {
let mut vars = HashSet::new();
expr_vars(expr, &mut vars);
if vars.len() != 1 || !var.with_str(|text| vars.contains(text)) {
return IndexArm::Decline;
}
let Some(seek) = leaf_seek(
var,
expr,
ctx.graph,
ctx.row,
ctx.params,
ctx.cypher_version,
) else {
return IndexArm::Decline;
};
if !seek.servable(ctx.graph, ctx.labels, ctx.label_seekable) {
return IndexArm::Unserved;
}
seek.serve(ctx.graph, ctx.labels)
.map_or(IndexArm::Unserved, IndexArm::Served)
}
pub(crate) fn node_candidates(
graph: &ExecGraph<'_>,
np: &NodePattern,
row: &Row,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
conjuncts: &[Expr],
) -> Result<Vec<NodeId>> {
funnel(
graph,
np,
row,
params,
cypher_version,
Ask {
conjuncts,
cap: None,
},
)
}
#[derive(Clone, Copy)]
struct Ask<'a> {
conjuncts: &'a [Expr],
cap: Option<usize>,
}
pub(crate) enum Capped {
Within(Vec<NodeId>),
Over,
}
pub(crate) fn node_candidates_capped(
graph: &ExecGraph<'_>,
np: &NodePattern,
row: &Row,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
conjuncts: &[Expr],
cap: usize,
) -> Result<Capped> {
let ask = Ask {
conjuncts,
cap: Some(cap),
};
let ids = funnel(graph, np, row, params, cypher_version, ask)?;
Ok(if ids.len() > cap {
Capped::Over
} else {
Capped::Within(ids)
})
}
fn funnel(
graph: &ExecGraph<'_>,
np: &NodePattern,
row: &Row,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
ask: Ask<'_>,
) -> Result<Vec<NodeId>> {
let reads_before = crate::ctx::node_reads();
let candidates = crate::ctx::phase_seek(|| {
binding_arm(
binding(np, row),
np,
ask,
graph,
row,
params,
cypher_version,
)
})?;
if crate::ctx::node_reads() == reads_before {
crate::ctx::count_node_reads(candidates.len() as u64);
}
Ok(candidates)
}
fn binding_arm(
class: NodeBinding<'_>,
np: &NodePattern,
ask: Ask<'_>,
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
) -> Result<Vec<NodeId>> {
let Ask { conjuncts, cap } = ask;
let props = || {
pattern_props(
graph,
row,
np.properties.as_ref(),
PatternMapRole::Match,
params,
cypher_version,
)
};
let v = match class {
Binding::Bound(id) => return Ok(vec![id]),
Binding::Mismatch => return Ok(Vec::new()),
Binding::Anonymous => return scan_ids(graph, np, props, cap),
Binding::Unbound(v) => v,
};
if np.force_scan {
return scan_ids(graph, np, || Ok(BTreeMap::new()), cap);
}
let label_seekable = label_index_seekable(np);
let disjunction_arms = np.static_disjunction_arms();
let mut seeks: Vec<Seek> = conjuncts
.iter()
.filter_map(|c| leaf_seek(v, c, graph, row, params, cypher_version))
.collect();
seeks.sort_by_key(Seek::rank);
let labels: Vec<String> = np.label_names().map(|label| label.to_string()).collect();
for seek in &seeks {
if let Some(arms) = &disjunction_arms {
if seek.indexed() {
if let Some(ids) = seek_union(graph, seek, arms)? {
return Ok(ids);
}
continue;
}
}
if !seek.servable(graph, &labels, label_seekable) {
continue;
}
if let Some(served) = seek.serve(graph, &labels) {
return served.narrowed(graph, &labels, props);
}
}
let ctx = OrCtx {
graph,
row,
params,
cypher_version,
labels: &labels,
label_seekable,
};
if let Some(served) = or_union_candidates(v, conjuncts, &ctx) {
return served.narrowed(graph, &labels, props);
}
scan_ids(graph, np, props, cap)
}
fn scan_ids(
graph: &ExecGraph<'_>,
np: &NodePattern,
props: impl FnOnce() -> Result<BTreeMap<String, Value>>,
cap: Option<usize>,
) -> Result<Vec<NodeId>> {
if label_index_seekable(np) {
let labels: Vec<String> = np.label_names().map(|label| label.to_string()).collect();
if let Some(ids) = graph.lookup_nodes_upto(&labels, &props()?, cap) {
return Ok(ids);
}
} else if let Some(arms) = np.static_disjunction_arms() {
if let Some(ids) = scan_disjunction_arms(graph, &arms, &props()?, cap)? {
return Ok(ids);
}
}
Ok(graph.all_node_ids())
}
fn scan_disjunction_arms(
graph: &ExecGraph<'_>,
arms: &DisjunctionArms<'_>,
props: &BTreeMap<String, Value>,
cap: Option<usize>,
) -> Result<Option<Vec<NodeId>>> {
if !props.is_empty() {
return union_dedup(arms.arms().map(|arm| {
let labels: Vec<String> = arm.map(|label| label.to_string()).collect();
graph
.lookup_nodes_upto(&labels, props, cap)
.expect("an arm's labels are non-empty: lookup_nodes always serves")
}))
.map(Some);
}
if !arms.base().is_empty() {
let labels: Vec<String> = arms.base().iter().map(|label| label.to_string()).collect();
return Ok(Some(graph.lookup_nodes_upto(&labels, props, cap).expect(
"the base labels are non-empty: lookup_nodes always serves",
)));
}
Ok(None)
}