use std::collections::{BTreeMap, HashMap, HashSet};
use relate_core::{temporal, NodeId, Result, Value};
use relate_ir::{is_pred_op, BinaryOp, Expr, NodePattern, PathPattern};
use relate_names::SmallName;
use relate_planner::Bound;
use crate::eval::{binary_pure, expr_vars};
use crate::overlay::{ExecGraph, ScanNode};
use crate::row::Row;
use super::pattern_policies::node_occurrence_counts;
#[cfg(test)]
use std::cell::Cell;
#[cfg(test)]
thread_local! {
static SPEC_DISABLED: Cell<bool> = const { Cell::new(false) };
static SPEC_GATES: Cell<u64> = const { Cell::new(0) };
}
#[cfg(test)]
pub(super) fn take_spec_gates() -> u64 {
SPEC_GATES.with(|count| count.replace(0))
}
#[cfg(test)]
pub(super) fn with_spec_disabled<R>(f: impl FnOnce() -> R) -> R {
super::test_support::with_flag_disabled(&SPEC_DISABLED, f)
}
#[cfg(test)]
fn spec_disabled() -> bool {
SPEC_DISABLED.with(Cell::get)
}
enum InlinePred {
Prop {
key: String,
kid: Option<u32>,
op: BinaryOp,
bound: Value,
},
Temporal {
ctor: String,
key: String,
kid: Option<u32>,
op: BinaryOp,
bound: Value,
},
}
impl InlinePred {
fn ok(&self, node: &ScanNode<'_>) -> Result<bool> {
let value = match self {
Self::Prop {
key,
kid,
op,
bound,
} => binary_pure(*op, node.prop(key, *kid), bound.clone())?,
Self::Temporal {
ctor,
key,
kid,
op,
bound,
} => {
let null = Value::Null;
let arg = node.prop_value(key, *kid).unwrap_or(&null);
let construct = || temporal::construct_named(ctor, std::slice::from_ref(arg));
let left = match (arg, ctor.as_str()) {
(Value::String(s), "date") => match temporal::padded_iso_date_value(s) {
Some(value) => value,
None => construct()?,
},
_ => construct()?,
};
binary_pure(*op, left, bound.clone())?
}
};
Ok(matches!(value, Value::Bool(true)))
}
fn compile(
graph: &ExecGraph<'_>,
var: &SmallName,
conjunct: &Expr,
params: &BTreeMap<String, Value>,
) -> Option<Self> {
let Expr::Binary { op, left, right } = conjunct else {
return None;
};
if !is_pred_op(*op) {
return None;
}
let bound = right.seek_value(params)?;
let (ctor, key, key_id) = match left.as_ref() {
Expr::Property { expr, key, key_id } if is_var(expr, var) => (None, key, *key_id),
Expr::Function {
name,
distinct: false,
args,
} if args.len() == 1 && name.with_str(temporal::is_constructor) => {
match &args[0] {
Expr::Property { expr, key, key_id } if is_var(expr, var) => {
(Some(name.to_string()), key, *key_id)
}
_ => return None,
}
}
_ => return None,
};
let kid = key.with_str(|text| graph.prop_key_id_resolved(text, key_id));
Some(match ctor {
None => Self::Prop {
key: key.to_string(),
kid,
op: *op,
bound,
},
Some(ctor) => Self::Temporal {
ctor,
key: key.to_string(),
kid,
op: *op,
bound,
},
})
}
}
fn is_var(expr: &Expr, var: &SmallName) -> bool {
matches!(expr, Expr::Variable(v) if v == var)
}
pub(crate) struct VarSpec {
labels: Vec<(String, Option<u32>)>,
preds: Vec<InlinePred>,
}
impl VarSpec {
fn ok(&self, node: &ScanNode<'_>) -> Result<bool> {
if !self
.labels
.iter()
.all(|(label, lid)| node.has_label(label, *lid))
{
return Ok(false);
}
for pred in &self.preds {
if !pred.ok(node)? {
return Ok(false);
}
}
Ok(true)
}
}
struct PathVars {
node_occurrences: HashMap<String, usize>,
rels: HashSet<String>,
}
impl PathVars {
fn of(path: &PathPattern) -> Self {
let mut rels = HashSet::new();
for rp in &path.rels {
if let Some(v) = &rp.variable {
rels.insert(v.to_string());
}
}
Self {
node_occurrences: node_occurrence_counts(path),
rels,
}
}
fn occurs_once(&self, var: &SmallName) -> bool {
var.with_str(|text| self.node_occurrences.get(text)) == Some(&1)
}
}
pub(crate) struct WalkSpec {
vars: HashMap<String, VarSpec>,
settled: Vec<usize>,
}
impl WalkSpec {
pub(crate) fn compile(
graph: &ExecGraph<'_>,
path: &PathPattern,
params: &BTreeMap<String, Value>,
conjuncts: &[Expr],
entry_bound: Bound<'_>,
) -> Self {
#[cfg(test)]
if spec_disabled() {
return Self {
vars: HashMap::new(),
settled: Vec::new(),
};
}
let path_vars = PathVars::of(path);
let mut settled = Vec::new();
let vars = path
.nodes
.iter()
.filter_map(|np| {
Self::compile_node(
graph,
np,
&path_vars,
params,
conjuncts,
entry_bound,
&mut settled,
)
})
.collect();
Self { vars, settled }
}
pub(crate) fn settled_conjuncts(&self) -> &[usize] {
&self.settled
}
fn compile_node(
graph: &ExecGraph<'_>,
np: &NodePattern,
path_vars: &PathVars,
params: &BTreeMap<String, Value>,
conjuncts: &[Expr],
entry_bound: Bound<'_>,
settled: &mut Vec<usize>,
) -> Option<(String, VarSpec)> {
let var = np.variable.as_ref()?;
if var.with_str(|text| entry_bound(text)) {
return None;
}
if !path_vars.occurs_once(var) {
return None;
}
if np.properties.is_some() {
return None;
}
if !np.has_static_labels() {
return None;
}
let (preds, mine) = Self::gate_conjuncts(graph, var, path_vars, params, conjuncts)?;
settled.extend(mine);
let labels = np
.labels
.iter()
.map(|(label, _)| {
(
label.to_string(),
label.with_str(|text| graph.base().label_id(text)),
)
})
.collect();
Some((var.to_string(), VarSpec { labels, preds }))
}
fn gate_conjuncts(
graph: &ExecGraph<'_>,
var: &SmallName,
path_vars: &PathVars,
params: &BTreeMap<String, Value>,
conjuncts: &[Expr],
) -> Option<(Vec<InlinePred>, Vec<usize>)> {
enum Class {
Owned,
Ahead,
Breaks,
}
let mut named = HashSet::new();
let mut preds = Vec::new();
let mut mine = Vec::new();
let mut gate_order_broken = false;
for (index, conjunct) in conjuncts.iter().enumerate() {
named.clear();
expr_vars(conjunct, &mut named);
let names_this_var = var.with_str(|text| named.contains(text));
let class = if named.len() == 1 && names_this_var {
Class::Owned
} else if !names_this_var
&& !named.is_empty()
&& !named.iter().any(|name| path_vars.rels.contains(name))
&& named
.iter()
.any(|name| path_vars.node_occurrences.contains_key(name))
{
Class::Ahead
} else {
Class::Breaks
};
match class {
Class::Owned => {
if gate_order_broken {
return None;
}
preds.push(InlinePred::compile(graph, var, conjunct, params)?);
mine.push(index);
}
Class::Ahead => {}
Class::Breaks => gate_order_broken = true,
}
}
if preds.is_empty() {
return None;
}
Some((preds, mine))
}
pub(crate) fn gate_spec<'s>(&'s self, np: &NodePattern, row: &Row) -> Option<&'s VarSpec> {
let var = np.variable.as_ref()?;
if var.with_str(|text| row.contains_key(text)) {
return None;
}
var.with_str(|text| self.vars.get(text))
}
}
pub(crate) fn candidate_ok(
graph: &ExecGraph<'_>,
gate: Option<&VarSpec>,
id: NodeId,
) -> Result<bool> {
match gate {
Some(spec) => {
#[cfg(test)]
SPEC_GATES.with(|count| count.set(count.get() + 1));
graph.node_scan_check(id, |node| spec.ok(&node))
}
None => Ok(true),
}
}
pub(crate) fn admit(
graph: &ExecGraph<'_>,
gate: Option<&VarSpec>,
id: NodeId,
np: &NodePattern,
row: &Row,
params: &BTreeMap<String, Value>,
) -> Result<bool> {
match gate {
Some(_) => Ok(true),
None => super::candidates::node_ok(graph, id, np, row, params),
}
}