1use std::borrow::Cow;
9use std::collections::BTreeMap;
10
11use relate_core::{Error, Result, Value};
12use relate_ir::{Expr, YieldItems};
13use relate_model::EntityKind;
14
15use crate::ctx::ExecCtx;
16use crate::eval::eval;
17use crate::exec::candidates::{materialize_candidate, resolve_search_index};
18use crate::graph::Procedure;
19use crate::procedure_registry::ProcSignature;
20use crate::row::Row;
21
22use super::fulltext;
23use super::ontology::{exec_ontology_call, OntologyProc};
24use super::procedure_rows::{builtin_procedure_rows, executable_signature, procedure_metadata};
25use super::vector::{vector_index_candidates, vector_operand, VectorSearchFilter};
26
27pub fn value_matches_proc_type(v: &Value, ty: &str) -> bool {
36 let ty = ty.trim().trim_end_matches('?').trim().to_ascii_uppercase();
37 if v.is_null() || ty.is_empty() || ty == "ANY" {
38 return true;
39 }
40 if ty.contains('|') {
43 return ty
44 .split('|')
45 .any(|alternative| value_matches_proc_type(v, alternative));
46 }
47 if ty == "LIST" || ty.starts_with("LIST<") {
51 return matches!(v, Value::List(_));
52 }
53 match ty.as_str() {
54 "STRING" => matches!(v, Value::String(_)),
55 "INTEGER" | "INT" => matches!(v, Value::Int(_)),
56 "FLOAT" => matches!(v, Value::Float(_) | Value::Int(_)),
57 "NUMBER" => matches!(v, Value::Int(_) | Value::Float(_)),
58 "BOOLEAN" | "BOOL" => matches!(v, Value::Bool(_)),
59 "MAP" => matches!(v, Value::Map(_)),
60 "NODE" => matches!(v, Value::Node(_)),
61 "RELATIONSHIP" | "REL" => matches!(v, Value::Relationship(_)),
62 "PATH" => matches!(v, Value::Path(_)),
63 "BYTES" => matches!(v, Value::Bytes(_)),
64 "DATE" | "DATETIME" | "LOCAL DATETIME" | "LOCALDATETIME" | "TIME" | "LOCAL TIME"
65 | "LOCALTIME" | "DURATION" => matches!(v, Value::Temporal(_)),
66 "POINT" => matches!(v, Value::Point(_)),
67 "UUID" => matches!(v, Value::Uuid(_)),
68 "VECTOR" => matches!(v, Value::Vector { .. }),
69 _ => false,
70 }
71}
72
73pub(crate) fn call_args_match(proc_val: &Value, given: &Value) -> bool {
74 proc_val.eq_non_null(given) || (proc_val.is_null() && given.is_null())
78}
79
80#[derive(Clone, Copy)]
82pub(crate) struct CallSpec<'a> {
83 pub name: &'a str,
84 pub args: &'a [Expr],
85 pub explicit: bool,
86 pub yield_items: &'a YieldItems,
87 pub optional: bool,
88 pub where_clause: Option<&'a Expr>,
89}
90
91pub fn check_explicit_arity(name: &str, required: usize, total: usize, given: usize) -> Result<()> {
97 if given < required || given > total {
98 return Err(Error::syntax(format!(
99 "InvalidNumberOfArguments: {name} expected {total}, got {given}"
100 )));
101 }
102 Ok(())
103}
104
105pub fn check_implicit_passing_mode(
115 explicit: bool,
116 required_args: usize,
117 has_yield: bool,
118) -> Result<()> {
119 if !explicit && required_args > 0 && has_yield {
120 return Err(Error::syntax(
121 "InvalidArgumentPassingMode: in-query CALL cannot pass arguments implicitly",
122 ));
123 }
124 Ok(())
125}
126
127pub(crate) fn void_optional_unit_row(rows_empty: bool, optional: bool) -> bool {
131 rows_empty && optional
132}
133
134pub(crate) fn compose_rows<'a>(
144 ctx: ExecCtx<'_>,
145 rows: Vec<Row>,
146 default_yields: &[&str],
147 yield_items: &YieldItems,
148 optional: bool,
149 where_clause: Option<&Expr>,
150 mut produce: impl FnMut(&Row) -> Result<Vec<Cow<'a, BTreeMap<String, Value>>>>,
151) -> Result<Vec<Row>> {
152 let ExecCtx {
153 graph,
154 params,
155 cypher_version,
156 ..
157 } = ctx;
158 let yields: Vec<(String, Option<String>)> = yield_items.resolved_pairs(default_yields);
159 let keys: Vec<String> = yields
162 .iter()
163 .map(|(column, alias)| alias.clone().unwrap_or_else(|| column.clone()))
164 .collect();
165 let mut out = Vec::new();
166 for input in rows {
167 let mut produced = 0usize;
168 for values in produce(&input)? {
169 let mut row = input.clone();
170 for ((column, _), key) in yields.iter().zip(&keys) {
171 row.insert(
172 key.clone(),
173 values.get(column).cloned().unwrap_or(Value::Null),
174 );
175 }
176 if where_clause
177 .map(|predicate| eval(graph, &row, predicate, params, cypher_version))
178 .transpose()?
179 .is_none_or(|value| value.truthy() == Some(true))
180 {
181 out.push(row);
182 produced += 1;
183 }
184 }
185 if produced == 0 && optional {
186 let mut row = input;
187 for key in &keys {
188 row.insert(key.clone(), Value::Null);
189 }
190 out.push(row);
191 }
192 }
193 Ok(out)
194}
195
196#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200enum VectorEntity {
201 Nodes,
202 Relationships,
203}
204
205impl VectorEntity {
206 fn relationship(self) -> bool {
207 self == VectorEntity::Relationships
208 }
209}
210
211enum CallDivert {
225 Ontology(OntologyProc),
227 Vector(VectorEntity),
230 FulltextQuery { relationship: bool },
233}
234
235#[cfg(test)]
239pub(crate) fn is_diverted_call(name: &str) -> bool {
240 divert_call(name).is_some()
241}
242
243fn divert_call(name: &str) -> Option<CallDivert> {
246 if let Ok(proc) = OntologyProc::try_from(name) {
247 return Some(CallDivert::Ontology(proc));
248 }
249 match crate::procedure_registry::builtin_procedure_signature(name)?.name {
253 "db.index.vector.queryNodes" => Some(CallDivert::Vector(VectorEntity::Nodes)),
254 "db.index.vector.queryRelationships" => {
255 Some(CallDivert::Vector(VectorEntity::Relationships))
256 }
257 "db.index.fulltext.queryNodes" => Some(CallDivert::FulltextQuery {
258 relationship: false,
259 }),
260 "db.index.fulltext.queryRelationships" => {
261 Some(CallDivert::FulltextQuery { relationship: true })
262 }
263 _ => None,
264 }
265}
266
267pub(super) fn check_ontology_call_contract(call: &CallSpec<'_>) -> Result<()> {
275 let signature = crate::procedure_registry::builtin_procedure_signature(call.name)
281 .ok_or_else(|| Error::procedure_not_found(call.name))?;
282 check_implicit_passing_mode(
285 call.explicit,
286 signature.required_args(),
287 call.yield_items.has_yield(),
288 )?;
289 if call.explicit {
290 check_explicit_arity(
291 call.name,
292 signature.required_args(),
293 signature.args.len(),
294 call.args.len(),
295 )?;
296 }
297 Ok(())
298}
299
300pub(crate) fn exec_call(
301 ctx: ExecCtx<'_>,
302 rows: Vec<Row>,
303 call: CallSpec<'_>,
304) -> Result<(Vec<Row>, bool)> {
305 let yields_unit = crate::exec::procedure_rows::executable_signature(call.name)
316 .is_some_and(ProcSignature::is_void);
317 match divert_call(call.name) {
318 Some(CallDivert::Ontology(proc)) => {
319 check_ontology_call_contract(&call)?;
320 exec_ontology_call(ctx, rows, call, proc).map(|rows| (rows, yields_unit))
321 }
322 Some(CallDivert::Vector(entity)) => {
323 exec_vector_query_call(ctx, rows, entity, call).map(|rows| (rows, yields_unit))
324 }
325 Some(CallDivert::FulltextQuery { relationship }) => {
326 exec_fulltext_query_call(ctx, rows, relationship, call).map(|rows| (rows, yields_unit))
327 }
328 None => exec_registry_call(ctx, rows, call),
329 }
330}
331
332enum CallRows<'a> {
337 Rows(Cow<'a, [BTreeMap<String, Value>]>),
338 PerRow(&'static ProcSignature),
339}
340
341struct ResolvedCall<'a> {
346 metadata: Cow<'a, Procedure>,
347 required_args: usize,
348 yields_unit: bool,
349 rows: CallRows<'a>,
350}
351
352fn exec_registry_call(
357 ctx: ExecCtx<'_>,
358 rows: Vec<Row>,
359 call: CallSpec<'_>,
360) -> Result<(Vec<Row>, bool)> {
361 let ExecCtx {
362 graph, principal, ..
363 } = ctx;
364 let CallSpec {
365 name,
366 args,
367 explicit,
368 yield_items,
369 optional,
370 where_clause,
371 } = call;
372 let registered = graph.procedure(name);
377 let resolved = match ®istered {
378 Some(procedure) => ResolvedCall {
379 yields_unit: procedure.yield_names.is_empty() && procedure.rows.is_empty(),
380 metadata: Cow::Borrowed(procedure),
381 required_args: procedure.arg_names.len(),
382 rows: CallRows::Rows(Cow::Borrowed(procedure.rows.as_slice())),
383 },
384 None => {
385 let signature =
386 executable_signature(name).ok_or_else(|| Error::procedure_not_found(name))?;
387 let rows = if signature.is_void() {
388 CallRows::Rows(Cow::Borrowed(&[]))
389 } else if signature.args.is_empty() {
390 CallRows::Rows(Cow::Owned(builtin_procedure_rows(
391 graph,
392 signature,
393 principal,
394 &BTreeMap::new(),
395 )?))
396 } else {
397 CallRows::PerRow(signature)
398 };
399 ResolvedCall {
400 yields_unit: signature.is_void(),
401 metadata: Cow::Owned(procedure_metadata(signature)),
402 required_args: signature.required_args(),
403 rows,
404 }
405 }
406 };
407 let ResolvedCall {
408 metadata,
409 required_args,
410 yields_unit,
411 rows: row_source,
412 } = resolved;
413 check_implicit_passing_mode(explicit, required_args, yield_items.has_yield())?;
417 if explicit {
418 check_explicit_arity(name, required_args, metadata.arg_names.len(), args.len())?;
419 }
420 if yields_unit && void_optional_unit_row(rows.is_empty(), optional) {
421 return Ok((vec![Row::new()], true));
422 }
423 let binding = CallBinding {
424 name,
425 source: if explicit {
426 CallArgsSource::Explicit(args)
427 } else {
428 CallArgsSource::Implicit
429 },
430 metadata: &metadata,
431 required_args,
432 ctx,
433 };
434 let mut out = Vec::new();
435 for row in &rows {
438 let call_args = binding.bind_row(row)?;
439 if yields_unit {
440 continue;
441 }
442 let proc_rows: Cow<'_, [BTreeMap<String, Value>]> = match &row_source {
449 CallRows::Rows(rows) => Cow::Borrowed(rows.as_ref()),
450 CallRows::PerRow(signature) => Cow::Owned(builtin_procedure_rows(
451 graph, signature, principal, &call_args,
452 )?),
453 };
454 let matched: Vec<_> = proc_rows
455 .iter()
456 .filter(|pr| {
457 metadata
458 .arg_names
459 .iter()
460 .all(|n| match (pr.get(n), call_args.get(n)) {
461 (Some(a), Some(b)) => call_args_match(a, b),
462 (None, _) => true,
463 _ => false,
464 })
465 })
466 .collect();
467 if matched.is_empty() && metadata.yield_names.is_empty() {
468 out.push(row.clone());
469 continue;
470 }
471 let default_yields: Vec<&str> = metadata.yield_names.iter().map(String::as_str).collect();
472 out.extend(compose_rows(
473 ctx,
474 vec![row.clone()],
475 &default_yields,
476 yield_items,
477 optional,
478 where_clause,
479 |_| Ok(matched.iter().map(|pr| Cow::Borrowed(*pr)).collect()),
484 )?);
485 }
486 Ok((if yields_unit { rows } else { out }, yields_unit))
487}
488
489enum CallArgsSource<'a> {
492 Explicit(&'a [Expr]),
493 Implicit,
494}
495
496struct CallBinding<'a> {
499 name: &'a str,
500 source: CallArgsSource<'a>,
501 metadata: &'a Procedure,
502 required_args: usize,
503 ctx: ExecCtx<'a>,
504}
505
506impl CallBinding<'_> {
507 fn bind_row(&self, row: &Row) -> Result<BTreeMap<String, Value>> {
512 if self.metadata.arg_types.len() != self.metadata.arg_names.len() {
516 return Err(Error::internal(format!(
517 "procedure '{}' declares {} arguments but {} types",
518 self.name,
519 self.metadata.arg_names.len(),
520 self.metadata.arg_types.len()
521 )));
522 }
523 let explicit = matches!(self.source, CallArgsSource::Explicit(_));
524 let args = match self.source {
525 CallArgsSource::Explicit(args) => args,
526 CallArgsSource::Implicit => &[],
527 };
528 if !explicit {
529 let missing_required = self
533 .metadata
534 .arg_names
535 .iter()
536 .take(self.required_args)
537 .any(|n| !self.ctx.params.contains_key(n) && !row.contains_key(n));
538 if missing_required {
539 return Err(Error::syntax(format!(
540 "MissingParameter: implicit args for {}",
541 self.name
542 )));
543 }
544 }
545 let mut call_args = BTreeMap::new();
546 for (index, (n, ty)) in self
547 .metadata
548 .arg_names
549 .iter()
550 .zip(self.metadata.arg_types.iter())
551 .enumerate()
552 {
553 let Some(value) = call_arg_value(&self.ctx, row, args, explicit, index, n)? else {
554 continue;
556 };
557 if !value_matches_proc_type(&value, ty) {
558 return Err(Error::syntax(format!(
559 "InvalidArgumentType: {} argument `{n}` expects {ty}",
560 self.name
561 )));
562 }
563 call_args.insert(n.clone(), value);
564 }
565 Ok(call_args)
566 }
567}
568
569pub(crate) fn call_arg_value(
574 ctx: &ExecCtx<'_>,
575 row: &Row,
576 args: &[Expr],
577 explicit: bool,
578 index: usize,
579 arg_name: &str,
580) -> Result<Option<Value>> {
581 if explicit {
582 args.get(index)
583 .map(|expr| eval(ctx.graph, row, expr, ctx.params, ctx.cypher_version))
584 .transpose()
585 } else {
586 Ok(ctx
587 .params
588 .get(arg_name)
589 .cloned()
590 .or_else(|| row.get(arg_name).cloned()))
591 }
592}
593
594pub(crate) fn exec_fulltext_query_call(
598 ctx: ExecCtx<'_>,
599 rows: Vec<Row>,
600 relationship: bool,
601 call: CallSpec<'_>,
602) -> Result<Vec<Row>> {
603 let CallSpec {
604 name,
605 args,
606 yield_items,
607 optional,
608 where_clause,
609 ..
610 } = call;
611 let ExecCtx {
612 graph,
613 params,
614 cypher_version,
615 ..
616 } = ctx;
617 if args.len() != 2 {
618 return Err(Error::syntax(format!(
619 "InvalidNumberOfArguments: {name} expected 2, got {}",
620 args.len()
621 )));
622 }
623 let entity_column = if relationship { "relationship" } else { "node" };
627 let score_key = "score";
628 let columns = [entity_column, score_key];
629 compose_rows(
630 ctx,
631 rows,
632 &columns,
633 yield_items,
634 optional,
635 where_clause,
636 |input| {
637 let index_name = eval(graph, input, &args[0], params, cypher_version)?
638 .as_string()
639 .ok_or_else(|| Error::invalid_argument_type("indexName must be STRING"))?
640 .to_string();
641 let query = eval(graph, input, &args[1], params, cypher_version)?
642 .as_string()
643 .ok_or_else(|| Error::invalid_argument_type("query must be STRING"))?
644 .to_string();
645 let (detail, _options) =
651 resolve_search_index(graph, &index_name, crate::redo::IndexKindSpec::Fulltext)?;
652 if detail.relationship != relationship {
653 return Err(Error::execution(
654 "WrongIndexType: fulltext index entity type mismatch",
655 ));
656 }
657 let kind = EntityKind::from_relationship_flag(detail.relationship);
661 let produced =
662 fulltext::search_all(graph, &detail, &query, fulltext::Analyzer::Standard)
663 .into_iter()
664 .map(|(id, score)| {
665 Cow::Owned(BTreeMap::from([
666 (
667 entity_column.to_string(),
668 materialize_candidate(graph, kind, id),
669 ),
670 (score_key.to_string(), Value::Float(score)),
671 ]))
672 })
673 .collect();
674 Ok(produced)
675 },
676 )
677}
678
679fn exec_vector_query_call(
680 ctx: ExecCtx<'_>,
681 rows: Vec<Row>,
682 entity: VectorEntity,
683 call: CallSpec<'_>,
684) -> Result<Vec<Row>> {
685 let relationship = entity.relationship();
686 let CallSpec {
687 name,
688 args,
689 yield_items,
690 optional,
691 where_clause,
692 ..
693 } = call;
694 let ExecCtx {
695 graph,
696 params,
697 cypher_version,
698 ..
699 } = ctx;
700 if args.len() != 3 {
701 return Err(Error::syntax(format!(
702 "InvalidNumberOfArguments: {name} expected 3, got {}",
703 args.len()
704 )));
705 }
706 let entity_column = if relationship { "relationship" } else { "node" };
709 compose_rows(
710 ctx,
711 rows,
712 &[entity_column, "score"],
713 yield_items,
714 optional,
715 where_clause,
716 |input| {
717 let index_name = eval(graph, input, &args[0], params, cypher_version)?
718 .as_string()
719 .ok_or_else(|| Error::invalid_argument_type("indexName must be STRING"))?
720 .to_string();
721 let limit = match eval(graph, input, &args[1], params, cypher_version)? {
722 Value::Int(value) if (1..=i32::MAX as i64).contains(&value) => value as usize,
723 _ => return Err(Error::ty(
724 "InvalidArgumentValue: numberOfNearestNeighbours must be a positive INTEGER",
725 )),
726 };
727 let query = eval(graph, input, &args[2], params, cypher_version)?;
728 let Some(query) = vector_operand(&query)? else {
729 return Ok(Vec::new());
730 };
731 let (index_kind, candidates) = vector_index_candidates(
732 ctx,
733 &index_name,
734 &query,
735 0,
736 limit,
737 VectorSearchFilter {
738 filters: &[],
739 input,
740 },
741 )?;
742 if index_kind.is_relationship() != relationship {
743 return Err(Error::execution(
744 "WrongIndexType: vector index entity type mismatch",
745 ));
746 }
747 let mut produced = Vec::new();
748 for (entity, score) in candidates {
749 produced.push(BTreeMap::from([
753 ("node".to_string(), entity.clone()),
754 ("relationship".to_string(), entity.clone()),
755 ("score".to_string(), Value::Float(score)),
756 ]));
757 }
758 Ok(produced.into_iter().map(Cow::Owned).collect())
759 },
760 )
761}
762
763#[cfg(test)]
764mod type_vocabulary_tests {
765 use super::value_matches_proc_type;
766 use relate_core::Value;
767
768 #[test]
772 fn list_type_accepts_only_list_or_list_generic() {
773 let list = Value::List(Vec::new().into());
774 assert!(value_matches_proc_type(&list, "LIST"));
775 assert!(value_matches_proc_type(&list, "LIST<FLOAT>"));
776 assert!(value_matches_proc_type(&list, "list<string>"));
777 assert!(!value_matches_proc_type(&list, "LISTS"));
778 assert!(!value_matches_proc_type(&list, "LISTING"));
779 assert!(!value_matches_proc_type(&Value::Int(1), "LISTS"));
780 }
781}
782
783#[cfg(test)]
784mod row_provenance_tests {
785 use crate::exec::test_support::{exec_autocommit, exec_cypher};
786 use crate::graph::Graph;
787 use relate_core::Value;
788
789 #[test]
793 fn a_no_argument_builtin_answers_its_rows_for_every_driving_row() {
794 let graph = Graph::default();
795 exec_autocommit(&graph, "CREATE (:User), (:Admin)").expect("the fixture's CREATE succeeds");
796
797 let result = exec_cypher(
798 &graph,
799 "UNWIND [1, 2] AS i CALL db.labels() YIELD label \
800 RETURN i, label ORDER BY i, label",
801 );
802 let string = |value: &str| Value::String(value.into());
803 assert_eq!(
804 result.rows,
805 vec![
806 vec![Value::Int(1), string("Admin")],
807 vec![Value::Int(1), string("User")],
808 vec![Value::Int(2), string("Admin")],
809 vec![Value::Int(2), string("User")],
810 ]
811 );
812 }
813
814 #[test]
818 fn an_argument_taking_builtin_produces_rows_from_each_rows_bindings() {
819 let graph = Graph::default();
820
821 let result = exec_cypher(
822 &graph,
823 "UNWIND [1, 2] AS i WITH i, 'GRAPH COUNTS' AS wanted \
824 CALL db.stats.retrieve(wanted) YIELD section RETURN i, section",
825 );
826 assert_eq!(
827 result.rows,
828 vec![
829 vec![Value::Int(1), Value::String("GRAPH COUNTS".into())],
830 vec![Value::Int(2), Value::String("GRAPH COUNTS".into())],
831 ]
832 );
833 }
834}