use std::cmp::Ordering as CmpOrdering;
use std::cmp::Reverse;
use std::collections::{BTreeMap, BinaryHeap};
use std::sync::Arc;
use relate_core::{Error, Node, NodeId, PropertyMap, RelId, Result, Value};
use relate_ir::{BinaryOp, Direction, Expr, NodePattern, RelPattern};
use relate_model::EntityKind;
use relate_names::{NamedToken, SmallName, Token};
use crate::eval::{eval_bound, label_expr_matches};
use crate::overlay::ExecGraph;
use crate::pattern_walk::{
id_fn_conversion, pattern_match_props, static_rel_type_ok, IdConversion,
};
use crate::props::props_all_match;
use crate::redo::{IndexDetailSpec, IndexKindSpec};
use crate::row::Row;
use crate::store::RelTypes;
pub(crate) fn rel_seek_expr(
var: &SmallName,
expr: &Expr,
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
) -> Option<RelId> {
let Expr::Binary { op, left, right } = expr else {
return None;
};
if !matches!(op, BinaryOp::Eq) {
return None;
}
let to_id: IdConversion = id_fn_conversion(var, left, relate_core::parse_rel_element_id)?;
let val = eval_bound(right, graph, row, params)?;
to_id.apply(&val)
}
pub(crate) enum SeekedRel {
Decline,
Gone,
Resolved {
start: NodeId,
end: NodeId,
rid: RelId,
},
}
pub(crate) fn resolve_rel_seek(
graph: &ExecGraph<'_>,
rp: &RelPattern,
types: &RelTypes,
conjuncts: &[Expr],
row: &Row,
params: &BTreeMap<String, Value>,
) -> SeekedRel {
if rp.var_length {
return SeekedRel::Decline;
}
let Some(v) = rp.variable.as_ref() else {
return SeekedRel::Decline;
};
let rid = match row.get_name(v) {
Some(Value::Relationship(r)) => r.id,
Some(_) => return SeekedRel::Decline,
None => match conjuncts
.iter()
.find_map(|c| rel_seek_expr(v, c, graph, row, params))
{
Some(rid) => rid,
None => return SeekedRel::Decline,
},
};
let Some((start, end)) = graph.rel_ends(rid) else {
return SeekedRel::Gone;
};
if !static_rel_type_ok(graph, rid, types) {
return SeekedRel::Gone;
}
SeekedRel::Resolved { start, end, rid }
}
pub(crate) fn oriented_start(rp: &RelPattern, start: NodeId, end: NodeId) -> Option<NodeId> {
match rp.direction {
Direction::Outgoing => Some(start),
Direction::Incoming => Some(end),
Direction::Both => None,
}
}
pub(crate) fn expect_enumerated_candidate<T>(candidate: Option<T>, id: i64) -> T {
candidate.unwrap_or_else(|| vanished_enumerated_candidate(id))
}
fn vanished_enumerated_candidate(id: i64) -> ! {
panic!("enumerated candidate {id} vanished from the read snapshot")
}
pub(crate) fn resolve_search_index(
graph: &ExecGraph<'_>,
index_name: &str,
expected_kind: IndexKindSpec,
) -> Result<(IndexDetailSpec, BTreeMap<String, Value>)> {
let theater = graph.show_schema()?;
let (detail, options) = match (
theater.data.index_details.get(index_name),
theater.data.index_options.get(index_name),
) {
(Some(detail), Some(options)) => (detail.clone(), options.clone()),
_ => return Err(Error::execution(format!("IndexDoesNotExist: {index_name}"))),
};
if detail.kind != expected_kind {
return Err(Error::execution(format!("WrongIndexType: {index_name}")));
}
if graph.index_created_in_scratch(index_name) {
return Err(Error::execution(format!(
"IndexStillPopulating: Index `{index_name}` is not ready yet. \
Wait until it finishes populating and retry the transaction."
)));
}
Ok((detail, options))
}
pub(crate) fn materialize_candidate(graph: &ExecGraph<'_>, kind: EntityKind, id: i64) -> Value {
let candidate = if kind.is_relationship() {
graph.rel(id).map(Value::from_relationship)
} else {
graph.node(id).map(Value::from_node)
};
expect_enumerated_candidate(candidate, id)
}
pub(crate) fn ranked_candidates(
graph: &ExecGraph<'_>,
kind: EntityKind,
ranked: impl IntoIterator<Item = (i64, f64)>,
) -> Vec<(Value, f64)> {
ranked
.into_iter()
.map(|(id, score)| (materialize_candidate(graph, kind, id), score))
.collect()
}
fn expect_enumerated_node(graph: &ExecGraph<'_>, id: NodeId) {
if !graph.node_exists(id) {
vanished_enumerated_candidate(id);
}
}
pub(crate) fn enumerated_node_prop(graph: &ExecGraph<'_>, id: NodeId, key: &str) -> Option<Value> {
let value = graph.node_prop(id, key);
if value.is_none() {
expect_enumerated_node(graph, id);
}
value
}
pub(crate) fn node_population_ids(graph: &ExecGraph<'_>, detail: &IndexDetailSpec) -> Vec<NodeId> {
let mut ids: Vec<NodeId> = detail
.labels
.iter()
.flat_map(|label| graph.live_node_ids_with_label(label))
.collect();
ids.sort_unstable();
ids.dedup();
ids
}
pub(crate) fn index_population(
graph: &ExecGraph<'_>,
detail: &IndexDetailSpec,
) -> Vec<(i64, Arc<PropertyMap>)> {
if detail.relationship {
graph
.all_rel_ids()
.into_iter()
.filter_map(|id| {
let rel_type = expect_enumerated_candidate(graph.rel_type(id), id);
if !detail.labels.iter().any(|label| label == &rel_type) {
return None;
}
let rel = expect_enumerated_candidate(graph.rel(id), id);
Some((id, Arc::clone(&rel.properties)))
})
.collect()
} else {
node_population_ids(graph, detail)
.into_iter()
.map(|id| {
let node = expect_enumerated_candidate(graph.node(id), id);
(id, Arc::clone(&node.properties))
})
.collect()
}
}
pub(crate) fn ranked_better_cmp(score_a: f64, id_a: i64, score_b: f64, id_b: i64) -> CmpOrdering {
score_a.total_cmp(&score_b).then_with(|| id_b.cmp(&id_a))
}
#[derive(Clone, Copy)]
struct Ranked {
score: f64,
id: i64,
}
impl Eq for Ranked {}
impl PartialEq for Ranked {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == CmpOrdering::Equal
}
}
impl Ord for Ranked {
fn cmp(&self, other: &Self) -> CmpOrdering {
ranked_better_cmp(self.score, self.id, other.score, other.id)
}
}
impl PartialOrd for Ranked {
fn partial_cmp(&self, other: &Self) -> Option<CmpOrdering> {
Some(self.cmp(other))
}
}
enum Admission {
Append(Ranked),
Replace(Ranked),
}
pub(crate) struct TopWindow {
worst_first: BinaryHeap<Reverse<Ranked>>,
offset: usize,
limit: usize,
window: usize,
}
impl TopWindow {
pub(crate) fn new(offset: usize, limit: usize) -> Self {
let window = offset.saturating_add(limit);
Self {
worst_first: BinaryHeap::with_capacity(window.min(1024)),
offset,
limit,
window,
}
}
pub(crate) fn vector_window(limit: usize) -> Self {
Self::new(0, limit)
}
fn admission_for(&self, score: f64, id: i64) -> Option<Admission> {
let candidate = Ranked { score, id };
if self.worst_first.len() < self.window {
return Some(Admission::Append(candidate));
}
self.worst_first
.peek()
.is_some_and(|worst| candidate > worst.0)
.then_some(Admission::Replace(candidate))
}
pub(crate) fn push_if_passes(
&mut self,
score: f64,
id: i64,
passes: impl FnOnce() -> Result<bool>,
) -> Result<()> {
let Some(admission) = self.admission_for(score, id) else {
return Ok(());
};
if passes()? {
self.enact(admission);
}
Ok(())
}
pub(crate) fn push(&mut self, score: f64, id: i64) {
if let Some(admission) = self.admission_for(score, id) {
self.enact(admission);
}
}
fn enact(&mut self, admission: Admission) {
match admission {
Admission::Append(candidate) => self.worst_first.push(Reverse(candidate)),
Admission::Replace(candidate) => {
*self
.worst_first
.peek_mut()
.expect("a full window has a worst entry") = Reverse(candidate);
}
}
}
pub(crate) fn into_sorted_rows(self) -> Vec<(i64, f64)> {
self.worst_first
.into_sorted_vec()
.into_iter()
.map(|Reverse(r)| (r.id, r.score))
.skip(self.offset)
.take(self.limit)
.collect()
}
}
pub(crate) fn node_ok(
graph: &ExecGraph<'_>,
id: NodeId,
np: &NodePattern,
row: &Row,
params: &BTreeMap<String, Value>,
) -> Result<bool> {
let snapshot: Option<Arc<Node>> =
np.variable
.as_ref()
.and_then(|v| row.get_name(v))
.and_then(|value| match value {
Value::Node(n) if n.id == id && graph.is_deleted_node(id) => Some(Arc::clone(n)),
_ => None,
});
let view = match snapshot.as_deref() {
Some(node) => ReadView::Tombstone(node),
None => ReadView::Store,
};
match &np.label_expr {
Some(expr) if expr.is_static_conjunction() => {
if !np
.labels
.iter()
.all(|(want, token)| view.has_label(graph, id, want, *token))
{
return Ok(false);
}
}
Some(expr) => {
let Some(labels) = view.labels(graph, id) else {
return Ok(false);
};
if !label_expr_matches(graph, row, params, expr, &labels, false)? {
return Ok(false);
}
}
None => {
if !view.visible(graph, id) {
return Ok(false);
}
}
}
let want = pattern_match_props(graph, row, np.properties.as_ref(), &np.prop_keys, params)?;
Ok(props_all_match(&want, |key| view.prop(graph, id, key)))
}
#[derive(Clone, Copy)]
enum ReadView<'a> {
Tombstone(&'a Node),
Store,
}
impl ReadView<'_> {
fn has_label(&self, graph: &ExecGraph<'_>, id: NodeId, want: &SmallName, token: Token) -> bool {
match self {
Self::Tombstone(node) => node.labels.iter().any(|have| want == have.as_str()),
Self::Store => {
let seen = want.with_str(|text| match token {
Token::Id(tid) => graph.node_has_label_id(id, tid.0, text),
Token::Unresolved => graph.node_has_label(id, text),
Token::Absent => graph.node_has_uninterned_label(id, text),
});
seen == Some(true)
}
}
}
fn labels(&self, graph: &ExecGraph<'_>, id: NodeId) -> Option<Vec<String>> {
match self {
Self::Tombstone(node) => Some((*node.labels).clone()),
Self::Store => graph.node_labels(id),
}
}
fn visible(&self, graph: &ExecGraph<'_>, id: NodeId) -> bool {
match self {
Self::Tombstone(_) => true,
Self::Store => graph.node_exists(id),
}
}
fn prop(&self, graph: &ExecGraph<'_>, id: NodeId, key: &NamedToken) -> Option<Value> {
match self {
Self::Tombstone(node) => key.0.with_str(|text| node.properties.get(text).cloned()),
Self::Store => graph.node_prop_resolved(id, key),
}
}
}