use std::collections::BTreeMap;
use std::sync::Arc;
use relate_core::{Error, NodeId, RelId, Result, Value};
use relate_ir::{pattern_prop_key, Expr, NodePattern, PathPattern, RelPattern};
use relate_names::NamedToken;
use crate::eval::{eval, label_expr_matches};
use crate::overlay::ExecGraph;
use crate::props::{admit_props, props_all_match, NullPolicy};
use crate::row::{Row, RowRung};
use crate::store::RelTypes;
use super::binds::commit_trail;
use super::{binding, hop_bounds, within_hop_bounds, PathRow, UsedRels, VarWalk};
pub(crate) fn map_from_expr(
graph: &ExecGraph<'_>,
row: &Row,
expr: &Expr,
role: PatternMapRole,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
) -> Result<BTreeMap<String, Value>> {
match eval(graph, row, expr, params, cypher_version)? {
Value::Map(m) => admit_props(Arc::unwrap_or_clone(m), role.nulls()),
Value::Null => Ok(BTreeMap::new()),
_ => Err(Error::ty("pattern properties must be a map")),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PatternMapRole {
Create,
Match,
}
impl PatternMapRole {
pub(crate) fn nulls(self) -> NullPolicy {
match self {
PatternMapRole::Create => NullPolicy::Drop,
PatternMapRole::Match => NullPolicy::KeepAsUnmatchable,
}
}
}
pub(crate) fn pattern_props(
graph: &ExecGraph<'_>,
row: &Row,
properties: Option<&Expr>,
role: PatternMapRole,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
) -> Result<BTreeMap<String, Value>> {
match properties {
Some(e) => map_from_expr(graph, row, e, role, params, cypher_version),
None => Ok(BTreeMap::new()),
}
}
pub(crate) fn pattern_match_props(
graph: &ExecGraph<'_>,
row: &Row,
properties: Option<&Expr>,
prop_keys: &[NamedToken],
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
) -> Result<Vec<(NamedToken, Value)>> {
let want = pattern_props(
graph,
row,
properties,
PatternMapRole::Match,
params,
cypher_version,
)?;
Ok(want
.into_iter()
.map(|(name, value)| (pattern_prop_key(prop_keys, &name), value))
.collect())
}
pub(crate) fn pattern_node_ok(
graph: &ExecGraph<'_>,
id: NodeId,
np: &NodePattern,
row: &Row,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
) -> Result<bool> {
match &np.label_expr {
Some(label_expr) => {
let Some(labels) = graph.node_labels(id) else {
return Ok(false);
};
if !label_expr_matches(
graph,
row,
params,
label_expr,
&labels,
false,
cypher_version,
)? {
return Ok(false);
}
}
None => {
if !graph.node_exists(id) {
return Ok(false);
}
}
}
let want = pattern_match_props(
graph,
row,
np.properties.as_ref(),
&np.prop_keys,
params,
cypher_version,
)?;
Ok(props_all_match(&want, |key| {
graph.node_prop_resolved(id, key)
}))
}
pub(crate) fn rel_props_ok(
graph: &ExecGraph<'_>,
rid: RelId,
rp: &RelPattern,
row: &Row,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
) -> Result<bool> {
let Some(props) = rp.properties.as_ref() else {
return Ok(true);
};
if !graph.rel_exists(rid) {
return Ok(false);
}
let want = pattern_match_props(
graph,
row,
Some(props),
&rp.prop_keys,
params,
cypher_version,
)?;
Ok(props_all_match(&want, |key| {
graph.rel_prop_resolved(rid, key)
}))
}
#[derive(Clone)]
pub(crate) struct RelFilter {
pub(crate) types: RelTypes,
pub(crate) type_expr_static: bool,
}
impl RelFilter {
pub(crate) fn resolve(graph: &ExecGraph<'_>, rp: &RelPattern) -> Self {
RelFilter {
types: graph.rel_types_of(rp),
type_expr_static: rp.type_expr_is_static_types(),
}
}
}
#[derive(Clone, Copy)]
pub(crate) struct RelHop<'p> {
pub(crate) pattern: &'p RelPattern,
pub(crate) filter: &'p RelFilter,
}
pub(crate) fn rel_edge_ok(
graph: &ExecGraph<'_>,
rid: RelId,
hop: RelHop<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
) -> Result<bool> {
let rp = hop.pattern;
if let Some(type_expr) = &rp.type_expr {
if !hop.filter.type_expr_static {
let Some(rel) = graph.rel_stub(rid) else {
return Ok(false);
};
if !label_expr_matches(
graph,
row,
params,
type_expr,
std::slice::from_ref(&rel.rel_type),
true,
cypher_version,
)? {
return Ok(false);
}
}
}
if !rel_props_ok(graph, rid, rp, row, params, cypher_version)? {
return Ok(false);
}
Ok(true)
}
pub(crate) fn static_rel_type_ok(graph: &ExecGraph<'_>, rid: RelId, types: &RelTypes) -> bool {
types.is_any() || graph.rel_type(rid).is_some_and(|t| types.matches_name(&t))
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn admit_hop(
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
cypher_version: Option<u32>,
hop: RelHop<'_>,
traverse: relate_ir::Direction,
used: &UsedRels,
trail: &[RelId],
current: NodeId,
rid: RelId,
) -> Result<Option<NodeId>> {
if used.contains(rid) || trail.contains(&rid) {
return Ok(None);
}
if !rel_edge_ok(graph, rid, hop, row, params, cypher_version)? {
return Ok(None);
}
Ok(graph.hop(current, rid, traverse))
}
pub(crate) fn bound_node(np: &NodePattern, row: &Row) -> Option<NodeId> {
binding(np, row).bound_id()
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn walk_exact_trail(
graph: &ExecGraph<'_>,
path: &PathPattern,
rel_idx: usize,
types: &RelTypes,
rung: &RowRung,
from: NodeId,
state: PathRow,
ids: &[RelId],
mut admit: impl FnMut(&Row, &UsedRels, &[RelId], NodeId, RelId) -> Result<Option<NodeId>>,
descend: impl FnOnce(Row, UsedRels, NodeId) -> Result<()>,
) -> Result<()> {
let rp = &path.rels[rel_idx];
let (min_h, max_h) = hop_bounds(rp);
if !within_hop_bounds(min_h, max_h, ids.len() as u32) {
return Ok(());
}
let PathRow { mut row, mut used } = state;
let mut current = from;
for (i, &rid) in ids.iter().enumerate() {
graph.cancel_tick()?;
if !static_rel_type_ok(graph, rid, types) {
return Ok(());
}
let Some(next) = admit(&row, &used, &ids[..i], current, rid)? else {
return Ok(());
};
current = next;
}
if !commit_trail(
&mut row,
&mut used,
rp,
ids,
graph,
rel_idx,
path.has_path_name(),
rung,
) {
return Ok(());
}
descend(row, used, current)
}
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
pub(crate) fn walk_var_length(
graph: &ExecGraph<'_>,
path: &PathPattern,
rel_idx: usize,
types: &RelTypes,
rung: &RowRung,
current: NodeId,
state: PathRow,
vw: VarWalk,
admit: &dyn Fn(&Row, &UsedRels, &[RelId], NodeId, RelId) -> Result<Option<NodeId>>,
descend: &mut dyn FnMut(Row, UsedRels, NodeId) -> Result<bool>,
) -> Result<bool> {
let PathRow { row, used } = state;
let VarWalk {
min_h,
max_h,
hops,
trail,
} = vw;
let rp = &path.rels[rel_idx];
let mut halted = false;
if within_hop_bounds(min_h, max_h, hops) {
let mut row2 = row.clone();
let mut used2 = used.clone();
if commit_trail(
&mut row2,
&mut used2,
rp,
&trail,
graph,
rel_idx,
path.has_path_name(),
rung,
) {
halted = descend(row2, used2, current)?;
}
}
if hops >= max_h || halted {
return Ok(halted);
}
let found = graph.try_find_neighbor_resolved::<Error>(current, rp.direction, types, |rid| {
graph.cancel_tick()?;
let Some(next) = admit(&row, &used, &trail, current, rid)? else {
return Ok(false);
};
let mut trail2 = trail.clone();
trail2.push(rid);
let halted = walk_var_length(
graph,
path,
rel_idx,
types,
rung,
next,
PathRow {
row: row.clone(),
used: used.clone(),
},
VarWalk {
min_h,
max_h,
hops: hops + 1,
trail: trail2,
},
admit,
descend,
)?;
Ok(halted)
})?;
Ok(found.is_some())
}