use std::collections::BTreeMap;
use relate_core::{NodeId, Result, Value};
use relate_ir::{
is_pred_op, pattern_prop_key, var_prop_named, BinaryOp, Expr, NodePattern, UnaryOp,
};
use relate_names::{NamedToken, SmallName, Token};
use crate::ctx::ExecCtx;
use crate::eval::bytecode::{NodeBytecode, PreparedBytecode};
use crate::eval::{binary_pure, bound_is_row_invariant, eval, orient, predicate_value_holds};
use crate::overlay::ExecGraph;
use crate::row::Row;
#[derive(Clone, Debug)]
pub(crate) enum Prog {
Bare,
Cmp {
key: NamedToken,
op: BinaryOp,
bound: Expr,
},
Null { key: NamedToken, is_null: bool },
Bytecode(NodeBytecode),
}
pub(crate) struct NodeTarget<'a> {
pub(crate) pattern: &'a NodePattern,
pub(crate) prog: Prog,
pub(crate) bytecode: Option<NodeBytecode>,
}
impl NodeTarget<'_> {
pub(crate) fn unfiltered(&self) -> bool {
self.pattern.labels.is_empty()
&& self.pattern.label_expr.is_none()
&& self.pattern.properties.is_none()
&& self.pattern.where_clause.is_none()
&& matches!(self.prog, Prog::Bare)
}
}
pub(crate) struct InternedLabels<'a> {
labels: &'a [(SmallName, Token)],
ids: Vec<Option<u32>>,
}
impl InternedLabels<'_> {
pub(crate) fn resolve<'a>(ctx: ExecCtx<'_>, pattern: &'a NodePattern) -> InternedLabels<'a> {
InternedLabels {
labels: &pattern.labels,
ids: pattern
.labels
.iter()
.map(|(label, token)| {
token.id_or_else(|| {
label.with_str(|text| ctx.graph.base().interned_label_id(text))
})
})
.collect(),
}
}
#[inline]
pub(crate) fn admits(&self, graph: &ExecGraph<'_>, node: NodeId) -> bool {
if self.labels.is_empty() {
return graph.node_exists(node);
}
self.labels
.iter()
.zip(&self.ids)
.all(|((label, _), id)| match id {
Some(id) => matches!(
label.with_str(|text| graph.node_has_label_id(node, *id, text)),
Some(true)
),
None => {
label.with_str(|text| graph.node_has_uninterned_label(node, text)) == Some(true)
}
})
}
}
pub(crate) trait NodePred: Copy {
type Prepared;
fn prepare(&self, ctx: ExecCtx<'_>) -> Result<Self::Prepared>;
fn check(&self, prepared: &mut Self::Prepared, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool>;
fn admits(
&self,
prepared: &mut Option<Self::Prepared>,
ctx: ExecCtx<'_>,
node: NodeId,
) -> Result<bool> {
if prepared.is_none() {
*prepared = Some(self.prepare(ctx)?);
}
self.check(
prepared.as_mut().expect("prepared before the check"),
ctx,
node,
)
}
}
pub(crate) trait PropCheck {
fn check_props(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool>;
}
pub(crate) struct PreparedPred<'a, C> {
labels: InternedLabels<'a>,
check: C,
}
impl<C: PropCheck> PreparedPred<'_, C> {
fn admits(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
if !self.labels.admits(ctx.graph, node) {
return Ok(false);
}
self.check.check_props(ctx, node)
}
}
pub(crate) struct CmpCheck<'a> {
key: &'a NamedToken,
op: BinaryOp,
value: Value,
}
impl PropCheck for CmpCheck<'_> {
fn check_props(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
if self.value.is_null() {
return Ok(false);
}
let have = ctx
.graph
.node_prop_resolved(node, self.key)
.unwrap_or(Value::Null);
if have.is_null() {
return Ok(false);
}
predicate_value_holds(&binary_pure(self.op, have, self.value.clone())?)
}
}
pub(crate) struct NullCheck<'a> {
key: &'a NamedToken,
is_null: bool,
}
impl PropCheck for NullCheck<'_> {
fn check_props(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
let is_null = ctx
.graph
.node_prop_resolved(node, self.key)
.is_none_or(|value: Value| value.is_null());
Ok(is_null == self.is_null)
}
}
impl PropCheck for PreparedBytecode<'_> {
fn check_props(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
self.admits(ctx, node)
}
}
pub(crate) enum AdmissionPrepared<'a> {
Bare(InternedLabels<'a>),
Cmp(PreparedPred<'a, CmpCheck<'a>>),
Null(PreparedPred<'a, NullCheck<'a>>),
Bytecode(PreparedPred<'a, PreparedBytecode<'a>>),
}
impl AdmissionPrepared<'_> {
fn admits(&mut self, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
match self {
AdmissionPrepared::Bare(labels) => Ok(labels.admits(ctx.graph, node)),
AdmissionPrepared::Cmp(prepared) => prepared.admits(ctx, node),
AdmissionPrepared::Null(prepared) => prepared.admits(ctx, node),
AdmissionPrepared::Bytecode(prepared) => prepared.admits(ctx, node),
}
}
}
impl<'a> NodePred for &'a NodeTarget<'a> {
type Prepared = AdmissionPrepared<'a>;
fn prepare(&self, ctx: ExecCtx<'_>) -> Result<Self::Prepared> {
let labels = InternedLabels::resolve(ctx, self.pattern);
Ok(match &self.prog {
Prog::Bare => AdmissionPrepared::Bare(labels),
Prog::Cmp { key, op, bound } => {
let value = eval(ctx.graph, &Row::new(), bound, ctx.params)?;
AdmissionPrepared::Cmp(PreparedPred {
labels,
check: CmpCheck {
key,
op: *op,
value,
},
})
}
Prog::Null { key, is_null } => AdmissionPrepared::Null(PreparedPred {
labels,
check: NullCheck {
key,
is_null: *is_null,
},
}),
Prog::Bytecode(code) => AdmissionPrepared::Bytecode(PreparedPred {
labels,
check: code.prepare(ctx)?,
}),
})
}
fn check(&self, prepared: &mut Self::Prepared, ctx: ExecCtx<'_>, node: NodeId) -> Result<bool> {
prepared.admits(ctx, node)
}
}
pub(crate) fn compile_node<'a>(
pattern: &'a NodePattern,
grouped: &BTreeMap<SmallName, Vec<&Expr>>,
) -> Option<NodeTarget<'a>> {
if pattern.where_clause.is_some() || !pattern.has_static_labels() {
return None;
}
let conjuncts = pattern
.variable
.as_ref()
.and_then(|var| grouped.get(var))
.map(Vec::as_slice)
.unwrap_or(&[]);
let map_entries: Vec<(NamedToken, &Expr)> = match &pattern.properties {
None => Vec::new(),
Some(Expr::Map(entries)) => {
let mut out = Vec::with_capacity(entries.len());
for (key, value) in entries {
if !bound_is_row_invariant(value) {
return None;
}
out.push((pattern_prop_key(&pattern.prop_keys, key), value));
}
out
}
Some(_) => return None,
};
let prog = match (map_entries.as_slice(), conjuncts) {
([], []) => Prog::Bare,
([(key, value)], []) => Prog::Cmp {
key: key.clone(),
op: BinaryOp::Eq,
bound: (*value).clone(),
},
([], [only]) => {
if let Some((_, prog)) = decode_conjunct(only) {
prog
} else {
Prog::Bytecode(NodeBytecode::compile_entries_and_exprs(
pattern.variable.as_ref(),
std::iter::empty(),
std::iter::once(*only),
)?)
}
}
_ => Prog::Bytecode(NodeBytecode::compile_entries_and_exprs(
pattern.variable.as_ref(),
map_entries,
conjuncts.iter().copied(),
)?),
};
let bytecode = match &prog {
Prog::Bare => None,
Prog::Bytecode(code) => Some(code.clone()),
Prog::Cmp { key, op, bound } => Some(NodeBytecode::from_cmp(key.clone(), *op, bound)?),
Prog::Null { key, is_null } => Some(NodeBytecode::from_null(key.clone(), *is_null)?),
};
Some(NodeTarget {
pattern,
prog,
bytecode,
})
}
pub(crate) fn decode_conjunct(expr: &Expr) -> Option<(String, Prog)> {
match expr {
Expr::Unary { op, expr } => {
let is_null = match op {
UnaryOp::IsNull => true,
UnaryOp::IsNotNull => false,
_ => return None,
};
let (var, key) = var_prop_named(expr)?;
Some((var.to_string(), Prog::Null { key, is_null }))
}
Expr::Binary { op, left, right } if is_pred_op(*op) => {
let ((var, key), other, op) = orient(var_prop_named, left, right, *op)?;
if !bound_is_row_invariant(other) {
return None;
}
Some((
var.to_string(),
Prog::Cmp {
key,
op,
bound: other.clone(),
},
))
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use relate_front::parse_and_lower;
use relate_ir::Clause;
use super::*;
fn where_conjuncts(cypher: &str) -> Vec<Expr> {
let query = parse_and_lower(cypher).unwrap();
let plan = relate_planner::plan(query, &mut |_| false).unwrap();
match &plan.parts[0][0] {
Clause::Match {
where_clause: Some(w),
..
} => crate::exec::pushdown::flatten_and_owned(w),
other => panic!("not a MATCH with WHERE: {other:?}"),
}
}
fn decoded(cypher: &str) -> Vec<Option<(String, Prog)>> {
where_conjuncts(cypher)
.iter()
.map(decode_conjunct)
.collect()
}
fn is_bare(prog: &Prog) -> bool {
matches!(prog, Prog::Bare)
}
#[test]
fn comparison_and_null_conjuncts_decode() {
let cases = decoded(
"MATCH (n) WHERE n.k > 1 AND n.s CONTAINS 'x' AND n.t STARTS WITH 'a' \
AND n.l IN [1, 2] AND n.z IS NOT NULL RETURN n",
);
assert_eq!(cases.len(), 5);
for case in &cases {
assert!(case.is_some(), "every conjunct decodes: {case:?}");
}
let Some((var, Prog::Cmp { op, .. })) = &cases[0] else {
panic!("first conjunct is a comparison");
};
assert_eq!(var, "n");
assert_eq!(*op, BinaryOp::Gt);
let Some((_, Prog::Null { is_null, .. })) = &cases[4] else {
panic!("last conjunct is a null check");
};
assert!(!*is_null);
}
#[test]
fn mirrored_comparisons_orient_instead_of_declining() {
let cases = decoded("MATCH (n) WHERE 1 < n.k RETURN n");
let Some((var, Prog::Cmp { op, .. })) = &cases[0] else {
panic!("a mirrored comparison orients");
};
assert_eq!(var, "n");
assert_eq!(*op, BinaryOp::Gt, "1 < n.k is n.k > 1");
}
#[test]
fn out_of_vocabulary_conjuncts_decline() {
let declines = [
"MATCH (n) WHERE n.a > n.b RETURN n",
"MATCH (n) WHERE size(n.k) > 3 RETURN n",
"MATCH (n) WHERE n.k > 1 OR n.j < 2 RETURN n",
"MATCH (n) WHERE NOT n.k > 1 RETURN n",
"MATCH (n) WHERE n.k > toInteger(rand()) RETURN n",
"MATCH (n) WHERE [1] IN n.k RETURN n",
];
for cypher in declines {
for case in decoded(cypher) {
assert!(case.is_none(), "{cypher} declines: {case:?}");
}
}
for case in decoded("MATCH (n) WHERE n.k > $min RETURN n") {
assert!(case.is_some(), "a parameter bound decodes");
}
}
#[test]
fn bare_and_clone_shapes() {
assert!(is_bare(&Prog::Bare));
let prog = Prog::Cmp {
key: ("k".into(), Token::Unresolved),
op: BinaryOp::Eq,
bound: Expr::Int(1),
};
assert!(matches!(prog.clone(), Prog::Cmp { .. }));
}
}