use std::borrow::Cow;
use std::collections::BTreeMap;
use relate_core::{Error, Result, Value};
use relate_ir::{Expr, YieldItems};
use relate_model::EntityKind;
use crate::ctx::ExecCtx;
use crate::eval::eval;
use crate::exec::candidates::{materialize_candidate, resolve_search_index};
use crate::graph::Procedure;
use crate::procedure_registry::ProcSignature;
use crate::row::Row;
use super::fulltext;
use super::ontology::{exec_ontology_call, OntologyProc};
use super::procedure_rows::{builtin_procedure_rows, executable_signature, procedure_metadata};
use super::vector::{vector_index_candidates, vector_operand, VectorSearchFilter};
pub fn value_matches_proc_type(v: &Value, ty: &str) -> bool {
let ty = ty.trim().trim_end_matches('?').trim().to_ascii_uppercase();
if v.is_null() || ty.is_empty() || ty == "ANY" {
return true;
}
if ty.contains('|') {
return ty
.split('|')
.any(|alternative| value_matches_proc_type(v, alternative));
}
if ty == "LIST" || ty.starts_with("LIST<") {
return matches!(v, Value::List(_));
}
match ty.as_str() {
"STRING" => matches!(v, Value::String(_)),
"INTEGER" | "INT" => matches!(v, Value::Int(_)),
"FLOAT" => matches!(v, Value::Float(_) | Value::Int(_)),
"NUMBER" => matches!(v, Value::Int(_) | Value::Float(_)),
"BOOLEAN" | "BOOL" => matches!(v, Value::Bool(_)),
"MAP" => matches!(v, Value::Map(_)),
"NODE" => matches!(v, Value::Node(_)),
"RELATIONSHIP" | "REL" => matches!(v, Value::Relationship(_)),
"PATH" => matches!(v, Value::Path(_)),
"BYTES" => matches!(v, Value::Bytes(_)),
"DATE" | "DATETIME" | "LOCAL DATETIME" | "LOCALDATETIME" | "TIME" | "LOCAL TIME"
| "LOCALTIME" | "DURATION" => matches!(v, Value::Temporal(_)),
"POINT" => matches!(v, Value::Point(_)),
"UUID" => matches!(v, Value::Uuid(_)),
"VECTOR" => matches!(v, Value::Vector { .. }),
_ => false,
}
}
pub(crate) fn call_args_match(proc_val: &Value, given: &Value) -> bool {
proc_val.eq_non_null(given) || (proc_val.is_null() && given.is_null())
}
#[derive(Clone, Copy)]
pub(crate) struct CallSpec<'a> {
pub name: &'a str,
pub args: &'a [Expr],
pub explicit: bool,
pub yield_items: &'a YieldItems,
pub optional: bool,
pub where_clause: Option<&'a Expr>,
}
pub fn check_explicit_arity(name: &str, required: usize, total: usize, given: usize) -> Result<()> {
if given < required || given > total {
return Err(Error::syntax(format!(
"InvalidNumberOfArguments: {name} expected {total}, got {given}"
)));
}
Ok(())
}
pub fn check_implicit_passing_mode(
explicit: bool,
required_args: usize,
has_yield: bool,
) -> Result<()> {
if !explicit && required_args > 0 && has_yield {
return Err(Error::syntax(
"InvalidArgumentPassingMode: in-query CALL cannot pass arguments implicitly",
));
}
Ok(())
}
pub(crate) fn void_optional_unit_row(rows_empty: bool, optional: bool) -> bool {
rows_empty && optional
}
pub(crate) fn compose_rows<'a>(
ctx: ExecCtx<'_>,
rows: Vec<Row>,
default_yields: &[&str],
yield_items: &YieldItems,
optional: bool,
where_clause: Option<&Expr>,
mut produce: impl FnMut(&Row) -> Result<Vec<Cow<'a, BTreeMap<String, Value>>>>,
) -> Result<Vec<Row>> {
let ExecCtx {
graph,
params,
cypher_version,
..
} = ctx;
let yields: Vec<(String, Option<String>)> = yield_items.resolved_pairs(default_yields);
let keys: Vec<String> = yields
.iter()
.map(|(column, alias)| alias.clone().unwrap_or_else(|| column.clone()))
.collect();
let mut out = Vec::new();
for input in rows {
let mut produced = 0usize;
for values in produce(&input)? {
let mut row = input.clone();
for ((column, _), key) in yields.iter().zip(&keys) {
row.insert(
key.clone(),
values.get(column).cloned().unwrap_or(Value::Null),
);
}
if where_clause
.map(|predicate| eval(graph, &row, predicate, params, cypher_version))
.transpose()?
.is_none_or(|value| value.truthy() == Some(true))
{
out.push(row);
produced += 1;
}
}
if produced == 0 && optional {
let mut row = input;
for key in &keys {
row.insert(key.clone(), Value::Null);
}
out.push(row);
}
}
Ok(out)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum VectorEntity {
Nodes,
Relationships,
}
impl VectorEntity {
fn relationship(self) -> bool {
self == VectorEntity::Relationships
}
}
enum CallDivert {
Ontology(OntologyProc),
Vector(VectorEntity),
FulltextQuery { relationship: bool },
}
#[cfg(test)]
pub(crate) fn is_diverted_call(name: &str) -> bool {
divert_call(name).is_some()
}
fn divert_call(name: &str) -> Option<CallDivert> {
if let Ok(proc) = OntologyProc::try_from(name) {
return Some(CallDivert::Ontology(proc));
}
match crate::procedure_registry::builtin_procedure_signature(name)?.name {
"db.index.vector.queryNodes" => Some(CallDivert::Vector(VectorEntity::Nodes)),
"db.index.vector.queryRelationships" => {
Some(CallDivert::Vector(VectorEntity::Relationships))
}
"db.index.fulltext.queryNodes" => Some(CallDivert::FulltextQuery {
relationship: false,
}),
"db.index.fulltext.queryRelationships" => {
Some(CallDivert::FulltextQuery { relationship: true })
}
_ => None,
}
}
pub(super) fn check_ontology_call_contract(call: &CallSpec<'_>) -> Result<()> {
let signature = crate::procedure_registry::builtin_procedure_signature(call.name)
.ok_or_else(|| Error::procedure_not_found(call.name))?;
check_implicit_passing_mode(
call.explicit,
signature.required_args(),
call.yield_items.has_yield(),
)?;
if call.explicit {
check_explicit_arity(
call.name,
signature.required_args(),
signature.args.len(),
call.args.len(),
)?;
}
Ok(())
}
pub(crate) fn exec_call(
ctx: ExecCtx<'_>,
rows: Vec<Row>,
call: CallSpec<'_>,
) -> Result<(Vec<Row>, bool)> {
let yields_unit = crate::exec::procedure_rows::executable_signature(call.name)
.is_some_and(ProcSignature::is_void);
match divert_call(call.name) {
Some(CallDivert::Ontology(proc)) => {
check_ontology_call_contract(&call)?;
exec_ontology_call(ctx, rows, call, proc).map(|rows| (rows, yields_unit))
}
Some(CallDivert::Vector(entity)) => {
exec_vector_query_call(ctx, rows, entity, call).map(|rows| (rows, yields_unit))
}
Some(CallDivert::FulltextQuery { relationship }) => {
exec_fulltext_query_call(ctx, rows, relationship, call).map(|rows| (rows, yields_unit))
}
None => exec_registry_call(ctx, rows, call),
}
}
enum CallRows<'a> {
Rows(Cow<'a, [BTreeMap<String, Value>]>),
PerRow(&'static ProcSignature),
}
struct ResolvedCall<'a> {
metadata: Cow<'a, Procedure>,
required_args: usize,
yields_unit: bool,
rows: CallRows<'a>,
}
fn exec_registry_call(
ctx: ExecCtx<'_>,
rows: Vec<Row>,
call: CallSpec<'_>,
) -> Result<(Vec<Row>, bool)> {
let ExecCtx {
graph, principal, ..
} = ctx;
let CallSpec {
name,
args,
explicit,
yield_items,
optional,
where_clause,
} = call;
let registered = graph.procedure(name);
let resolved = match ®istered {
Some(procedure) => ResolvedCall {
yields_unit: procedure.yield_names.is_empty() && procedure.rows.is_empty(),
metadata: Cow::Borrowed(procedure),
required_args: procedure.arg_names.len(),
rows: CallRows::Rows(Cow::Borrowed(procedure.rows.as_slice())),
},
None => {
let signature =
executable_signature(name).ok_or_else(|| Error::procedure_not_found(name))?;
let rows = if signature.is_void() {
CallRows::Rows(Cow::Borrowed(&[]))
} else if signature.args.is_empty() {
CallRows::Rows(Cow::Owned(builtin_procedure_rows(
graph,
signature,
principal,
&BTreeMap::new(),
)?))
} else {
CallRows::PerRow(signature)
};
ResolvedCall {
yields_unit: signature.is_void(),
metadata: Cow::Owned(procedure_metadata(signature)),
required_args: signature.required_args(),
rows,
}
}
};
let ResolvedCall {
metadata,
required_args,
yields_unit,
rows: row_source,
} = resolved;
check_implicit_passing_mode(explicit, required_args, yield_items.has_yield())?;
if explicit {
check_explicit_arity(name, required_args, metadata.arg_names.len(), args.len())?;
}
if yields_unit && void_optional_unit_row(rows.is_empty(), optional) {
return Ok((vec![Row::new()], true));
}
let binding = CallBinding {
name,
source: if explicit {
CallArgsSource::Explicit(args)
} else {
CallArgsSource::Implicit
},
metadata: &metadata,
required_args,
ctx,
};
let mut out = Vec::new();
for row in &rows {
let call_args = binding.bind_row(row)?;
if yields_unit {
continue;
}
let proc_rows: Cow<'_, [BTreeMap<String, Value>]> = match &row_source {
CallRows::Rows(rows) => Cow::Borrowed(rows.as_ref()),
CallRows::PerRow(signature) => Cow::Owned(builtin_procedure_rows(
graph, signature, principal, &call_args,
)?),
};
let matched: Vec<_> = proc_rows
.iter()
.filter(|pr| {
metadata
.arg_names
.iter()
.all(|n| match (pr.get(n), call_args.get(n)) {
(Some(a), Some(b)) => call_args_match(a, b),
(None, _) => true,
_ => false,
})
})
.collect();
if matched.is_empty() && metadata.yield_names.is_empty() {
out.push(row.clone());
continue;
}
let default_yields: Vec<&str> = metadata.yield_names.iter().map(String::as_str).collect();
out.extend(compose_rows(
ctx,
vec![row.clone()],
&default_yields,
yield_items,
optional,
where_clause,
|_| Ok(matched.iter().map(|pr| Cow::Borrowed(*pr)).collect()),
)?);
}
Ok((if yields_unit { rows } else { out }, yields_unit))
}
enum CallArgsSource<'a> {
Explicit(&'a [Expr]),
Implicit,
}
struct CallBinding<'a> {
name: &'a str,
source: CallArgsSource<'a>,
metadata: &'a Procedure,
required_args: usize,
ctx: ExecCtx<'a>,
}
impl CallBinding<'_> {
fn bind_row(&self, row: &Row) -> Result<BTreeMap<String, Value>> {
if self.metadata.arg_types.len() != self.metadata.arg_names.len() {
return Err(Error::internal(format!(
"procedure '{}' declares {} arguments but {} types",
self.name,
self.metadata.arg_names.len(),
self.metadata.arg_types.len()
)));
}
let explicit = matches!(self.source, CallArgsSource::Explicit(_));
let args = match self.source {
CallArgsSource::Explicit(args) => args,
CallArgsSource::Implicit => &[],
};
if !explicit {
let missing_required = self
.metadata
.arg_names
.iter()
.take(self.required_args)
.any(|n| !self.ctx.params.contains_key(n) && !row.contains_key(n));
if missing_required {
return Err(Error::syntax(format!(
"MissingParameter: implicit args for {}",
self.name
)));
}
}
let mut call_args = BTreeMap::new();
for (index, (n, ty)) in self
.metadata
.arg_names
.iter()
.zip(self.metadata.arg_types.iter())
.enumerate()
{
let Some(value) = call_arg_value(&self.ctx, row, args, explicit, index, n)? else {
continue;
};
if !value_matches_proc_type(&value, ty) {
return Err(Error::syntax(format!(
"InvalidArgumentType: {} argument `{n}` expects {ty}",
self.name
)));
}
call_args.insert(n.clone(), value);
}
Ok(call_args)
}
}
pub(crate) fn call_arg_value(
ctx: &ExecCtx<'_>,
row: &Row,
args: &[Expr],
explicit: bool,
index: usize,
arg_name: &str,
) -> Result<Option<Value>> {
if explicit {
args.get(index)
.map(|expr| eval(ctx.graph, row, expr, ctx.params, ctx.cypher_version))
.transpose()
} else {
Ok(ctx
.params
.get(arg_name)
.cloned()
.or_else(|| row.get(arg_name).cloned()))
}
}
pub(crate) fn exec_fulltext_query_call(
ctx: ExecCtx<'_>,
rows: Vec<Row>,
relationship: bool,
call: CallSpec<'_>,
) -> Result<Vec<Row>> {
let CallSpec {
name,
args,
yield_items,
optional,
where_clause,
..
} = call;
let ExecCtx {
graph,
params,
cypher_version,
..
} = ctx;
if args.len() != 2 {
return Err(Error::syntax(format!(
"InvalidNumberOfArguments: {name} expected 2, got {}",
args.len()
)));
}
let entity_column = if relationship { "relationship" } else { "node" };
let score_key = "score";
let columns = [entity_column, score_key];
compose_rows(
ctx,
rows,
&columns,
yield_items,
optional,
where_clause,
|input| {
let index_name = eval(graph, input, &args[0], params, cypher_version)?
.as_string()
.ok_or_else(|| Error::invalid_argument_type("indexName must be STRING"))?
.to_string();
let query = eval(graph, input, &args[1], params, cypher_version)?
.as_string()
.ok_or_else(|| Error::invalid_argument_type("query must be STRING"))?
.to_string();
let (detail, _options) =
resolve_search_index(graph, &index_name, crate::redo::IndexKindSpec::Fulltext)?;
if detail.relationship != relationship {
return Err(Error::execution(
"WrongIndexType: fulltext index entity type mismatch",
));
}
let kind = EntityKind::from_relationship_flag(detail.relationship);
let produced =
fulltext::search_all(graph, &detail, &query, fulltext::Analyzer::Standard)
.into_iter()
.map(|(id, score)| {
Cow::Owned(BTreeMap::from([
(
entity_column.to_string(),
materialize_candidate(graph, kind, id),
),
(score_key.to_string(), Value::Float(score)),
]))
})
.collect();
Ok(produced)
},
)
}
fn exec_vector_query_call(
ctx: ExecCtx<'_>,
rows: Vec<Row>,
entity: VectorEntity,
call: CallSpec<'_>,
) -> Result<Vec<Row>> {
let relationship = entity.relationship();
let CallSpec {
name,
args,
yield_items,
optional,
where_clause,
..
} = call;
let ExecCtx {
graph,
params,
cypher_version,
..
} = ctx;
if args.len() != 3 {
return Err(Error::syntax(format!(
"InvalidNumberOfArguments: {name} expected 3, got {}",
args.len()
)));
}
let entity_column = if relationship { "relationship" } else { "node" };
compose_rows(
ctx,
rows,
&[entity_column, "score"],
yield_items,
optional,
where_clause,
|input| {
let index_name = eval(graph, input, &args[0], params, cypher_version)?
.as_string()
.ok_or_else(|| Error::invalid_argument_type("indexName must be STRING"))?
.to_string();
let limit = match eval(graph, input, &args[1], params, cypher_version)? {
Value::Int(value) if (1..=i32::MAX as i64).contains(&value) => value as usize,
_ => return Err(Error::ty(
"InvalidArgumentValue: numberOfNearestNeighbours must be a positive INTEGER",
)),
};
let query = eval(graph, input, &args[2], params, cypher_version)?;
let Some(query) = vector_operand(&query)? else {
return Ok(Vec::new());
};
let (index_kind, candidates) = vector_index_candidates(
ctx,
&index_name,
&query,
0,
limit,
VectorSearchFilter {
filters: &[],
input,
},
)?;
if index_kind.is_relationship() != relationship {
return Err(Error::execution(
"WrongIndexType: vector index entity type mismatch",
));
}
let mut produced = Vec::new();
for (entity, score) in candidates {
produced.push(BTreeMap::from([
("node".to_string(), entity.clone()),
("relationship".to_string(), entity.clone()),
("score".to_string(), Value::Float(score)),
]));
}
Ok(produced.into_iter().map(Cow::Owned).collect())
},
)
}
#[cfg(test)]
mod type_vocabulary_tests {
use super::value_matches_proc_type;
use relate_core::Value;
#[test]
fn list_type_accepts_only_list_or_list_generic() {
let list = Value::List(Vec::new().into());
assert!(value_matches_proc_type(&list, "LIST"));
assert!(value_matches_proc_type(&list, "LIST<FLOAT>"));
assert!(value_matches_proc_type(&list, "list<string>"));
assert!(!value_matches_proc_type(&list, "LISTS"));
assert!(!value_matches_proc_type(&list, "LISTING"));
assert!(!value_matches_proc_type(&Value::Int(1), "LISTS"));
}
}
#[cfg(test)]
mod row_provenance_tests {
use crate::exec::test_support::{exec_autocommit, exec_cypher};
use crate::graph::Graph;
use relate_core::Value;
#[test]
fn a_no_argument_builtin_answers_its_rows_for_every_driving_row() {
let graph = Graph::default();
exec_autocommit(&graph, "CREATE (:User), (:Admin)").expect("the fixture's CREATE succeeds");
let result = exec_cypher(
&graph,
"UNWIND [1, 2] AS i CALL db.labels() YIELD label \
RETURN i, label ORDER BY i, label",
);
let string = |value: &str| Value::String(value.into());
assert_eq!(
result.rows,
vec![
vec![Value::Int(1), string("Admin")],
vec![Value::Int(1), string("User")],
vec![Value::Int(2), string("Admin")],
vec![Value::Int(2), string("User")],
]
);
}
#[test]
fn an_argument_taking_builtin_produces_rows_from_each_rows_bindings() {
let graph = Graph::default();
let result = exec_cypher(
&graph,
"UNWIND [1, 2] AS i WITH i, 'GRAPH COUNTS' AS wanted \
CALL db.stats.retrieve(wanted) YIELD section RETURN i, section",
);
assert_eq!(
result.rows,
vec![
vec![Value::Int(1), Value::String("GRAPH COUNTS".into())],
vec![Value::Int(2), Value::String("GRAPH COUNTS".into())],
]
);
}
}