relate_executor/exec/procedures.rs
1//! `CALL` procedure execution: registered + built-in procedures,
2//! fulltext and vector index query procedures. The dispatch path
3//! classifies a `CALL` name once ([`divert_call`]): a specialized executor
4//! (ontology, vector, fulltext) or the generic registry fallback. The
5//! built-in procedure row producers live in the sibling `procedure_rows`
6//! module.
7
8use std::borrow::Cow;
9use std::collections::BTreeMap;
10
11use relate_core::{Error, Result, Value};
12use relate_ir::{CallArgs, Clause, Expr, YieldItems};
13use relate_model::EntityKind;
14use relate_names::SmallName;
15
16use crate::ctx::ExecCtx;
17use crate::eval::{eval, where_clause_holds};
18use crate::exec::candidates::{materialize_candidate, resolve_search_index};
19use crate::graph::{Procedure, QueryStats};
20use crate::procedure_registry::ProcSignature;
21use crate::row::Row;
22
23use super::fulltext;
24use super::ontology::{exec_ontology_call, OntologyProc};
25use super::procedure_rows::{builtin_procedure_rows, executable_signature, procedure_metadata};
26use super::scope::star_scope_names;
27use super::vector::{vector_index_candidates, vector_operand, VectorSearchFilter};
28use super::QueryResult;
29
30/// Whether a value satisfies a procedure argument type string (`STRING`,
31/// `INTEGER`, `LIST<FLOAT>`, …). `ANY`, an empty type, a nullable `?`
32/// suffix, and a null value match everything; the accepted type vocabulary
33/// is explicit and fails closed, so an unknown (typo'd or unmodelled) type
34/// name matches nothing. The precise element-type check of a list happens
35/// in the procedure body itself. Used by the executor's `CALL` dispatch
36/// and re-exported for `relate::Database`'s compile-time call
37/// validation.
38pub fn value_matches_proc_type(v: &Value, ty: &str) -> bool {
39 let ty = ty.trim().trim_end_matches('?').trim().to_ascii_uppercase();
40 if v.is_null() || ty.is_empty() || ty == "ANY" {
41 return true;
42 }
43 // A signature may declare several admissible types (`BOOLEAN|MAP`, the
44 // Cypher 25 and legacy forms of one argument).
45 if ty.contains('|') {
46 return ty
47 .split('|')
48 .any(|alternative| value_matches_proc_type(v, alternative));
49 }
50 // The accepted type vocabulary is explicit and fails closed: an unknown
51 // (typo'd or unmodelled) name does not silently disable checking.
52 // Generic lists (`LIST<FLOAT>`, `LIST<NODE>`, …) share the list check.
53 if ty == "LIST" || ty.starts_with("LIST<") {
54 return matches!(v, Value::List(_));
55 }
56 match ty.as_str() {
57 "STRING" => matches!(v, Value::String(_)),
58 "INTEGER" | "INT" => matches!(v, Value::Int(_)),
59 "FLOAT" => matches!(v, Value::Float(_) | Value::Int(_)),
60 "NUMBER" => matches!(v, Value::Int(_) | Value::Float(_)),
61 "BOOLEAN" | "BOOL" => matches!(v, Value::Bool(_)),
62 "MAP" => matches!(v, Value::Map(_)),
63 "NODE" => matches!(v, Value::Node(_)),
64 "RELATIONSHIP" | "REL" => matches!(v, Value::Relationship(_)),
65 "PATH" => matches!(v, Value::Path(_)),
66 "BYTES" => matches!(v, Value::Bytes(_)),
67 "DATE" | "DATETIME" | "LOCAL DATETIME" | "LOCALDATETIME" | "TIME" | "LOCAL TIME"
68 | "LOCALTIME" | "DURATION" => matches!(v, Value::Temporal(_)),
69 "POINT" => matches!(v, Value::Point(_)),
70 "UUID" => matches!(v, Value::Uuid(_)),
71 "VECTOR" => matches!(v, Value::Vector { .. }),
72 _ => false,
73 }
74}
75
76pub(crate) fn call_args_match(proc_val: &Value, given: &Value) -> bool {
77 // `eq_non_null` already covers the Int/Float cross-comparison with the
78 // exact rule (`relate_model::canonical_key::eq_i64_f64`); a separate
79 // `as f64` fallback here would reintroduce the lossy cast.
80 proc_val.eq_non_null(given) || (proc_val.is_null() && given.is_null())
81}
82
83/// Static shape of a `CALL` clause (name, arguments, yields, optionality).
84#[derive(Clone, Copy)]
85pub(crate) struct CallSpec<'a> {
86 pub name: &'a str,
87 /// The call's one passing-mode value — the IR's owned [`CallArgs`],
88 /// lowered once by the front end — borrowed for the call's run, so
89 /// no consumer re-encodes the mode as a bool beside a bare slice.
90 pub source: &'a CallArgs,
91 pub yield_items: &'a YieldItems,
92 pub optional: bool,
93 pub where_clause: Option<&'a Expr>,
94}
95
96impl<'a> CallSpec<'a> {
97 /// The one runtime `CALL` contract every dispatch path reads: the
98 /// implicit-passing-mode backstop, then the arity, over the
99 /// (required, total) pair the call's signature declares — the
100 /// generic registry path passes its resolved pair
101 /// ([`exec_registry_call`]), the diverted executors their canonical
102 /// registry signature's ([`Self::check_registry_contract`]). Every
103 /// path consults the same two predicates through this one method,
104 /// never a hand-rebuilt arity half (stellar round 2, F-2-26).
105 ///
106 /// Answers the positional slice a value-taking executor reads: the
107 /// explicit list, its length the arity check validated, or the
108 /// empty slice a paren-less call passes by the grammar — that form
109 /// has no positional arity at all, its arguments resolving by name
110 /// (the generic binder's missing-name rejection; the facade states
111 /// the same policy at compile time).
112 pub(crate) fn check_contract(&self, required: usize, total: usize) -> Result<&'a [Expr]> {
113 check_implicit_passing_mode(
114 self.source.is_explicit(),
115 required,
116 self.yield_items.has_yield(),
117 )?;
118 match self.source {
119 CallArgs::Explicit(args) => {
120 check_explicit_arity(self.name, required, total, args.len())?;
121 Ok(args)
122 }
123 CallArgs::Implicit => Ok(&[]),
124 }
125 }
126
127 /// The diverted-name contract — [`Self::check_contract`] over the
128 /// name's canonical registry signature. The `db.ontology.*` divert
129 /// reads this at its dispatch site: its executor resolves arguments
130 /// by name, so the paren-less form carries no positional arity
131 /// there (the runtime contract the generic path enforces, from the
132 /// ONE registry signature).
133 pub(crate) fn check_registry_contract(&self) -> Result<()> {
134 let signature = diverted_signature(self.name)?;
135 self.check_contract(signature.required_args(), signature.args.len())
136 .map(|_| ())
137 }
138
139 /// The diverted scan executors' contract — the vector and fulltext
140 /// `db.index.*.query*` calls, whose scans read their arguments
141 /// positionally and resolve no names: [`Self::check_registry_contract`]'s
142 /// pair plus the positional form itself, so a paren-less call —
143 /// which passes no list — answers the arity rejection exactly like
144 /// a short explicit one (`expected 3, got 0`), never a positional
145 /// read off an empty slice (stellar round 2, F-2-43). Answers the
146 /// validated positional slice.
147 pub(crate) fn check_positional_contract(&self) -> Result<&'a [Expr]> {
148 let signature = diverted_signature(self.name)?;
149 let args = self.check_contract(signature.required_args(), signature.args.len())?;
150 match self.source {
151 CallArgs::Explicit(_) => Ok(args),
152 CallArgs::Implicit => check_explicit_arity(
153 self.name,
154 signature.required_args(),
155 signature.args.len(),
156 0,
157 )
158 .map(|()| args),
159 }
160 }
161}
162
163/// The canonical registry signature a diverted name classified by —
164/// the divert's own lookup, answered again for the contract it checks.
165/// The diverted names are statically registered (pinned by test), so a
166/// miss is the fail-closed `ProcedureNotFound`, never a silent
167/// fall-through.
168fn diverted_signature(name: &str) -> Result<&'static ProcSignature> {
169 crate::procedure_registry::builtin_procedure_signature(name)
170 .ok_or_else(|| Error::procedure_not_found(name))
171}
172
173/// The registry-driven explicit-arity check — one half of the runtime
174/// `CALL` contract ([`CallSpec::check_contract`]), which every dispatch
175/// path (the generic registry path, the ontology divert, the vector and
176/// fulltext scans) reads: an explicit call passes between `required`
177/// and `total` arguments. (The facade's compile-time `validate_calls`
178/// already enforces the same contract.)
179pub fn check_explicit_arity(name: &str, required: usize, total: usize, given: usize) -> Result<()> {
180 if given < required || given > total {
181 return Err(Error::syntax(format!(
182 "InvalidNumberOfArguments: {name} expected {total}, got {given}"
183 )));
184 }
185 Ok(())
186}
187
188/// The passing-mode backstop — the other half of the runtime `CALL`
189/// contract ([`CallSpec::check_contract`]): an in-query implicit
190/// call — a `CALL` with a YIELD, in a clause pipeline — cannot pass
191/// arguments; the procedure's arguments resolve only in a standalone unit
192/// call. `required_args` is the caller's registry truth: the number of
193/// declared parameters *without a default* (LABS-389: a procedure whose
194/// parameters all carry defaults is callable implicitly). (The facade's
195/// compile-time `validate_calls` enforces the same contract before
196/// execution; this is the executor-side backstop.)
197pub fn check_implicit_passing_mode(
198 explicit: bool,
199 required_args: usize,
200 has_yield: bool,
201) -> Result<()> {
202 if !explicit && required_args > 0 && has_yield {
203 return Err(Error::syntax(
204 "InvalidArgumentPassingMode: in-query CALL cannot pass arguments implicitly",
205 ));
206 }
207 Ok(())
208}
209
210/// The generic void-procedure contract: an OPTIONAL `CALL` with no return
211/// columns over no input rows yields one unit row. Callers gate on the
212/// void shape themselves.
213pub(crate) fn void_optional_unit_row(rows_empty: bool, optional: bool) -> bool {
214 rows_empty && optional
215}
216
217/// Row composition shared by every built-in row-producing procedure
218/// executor (the generic registry path, fulltext, vector and
219/// `db.ontology.get`): resolve the effective YIELD list (the caller's
220/// `yield_items`, or — when empty or `*`-containing — `default_yields`),
221/// then per input row and per produced column→value map, clone the input,
222/// insert each yielded cell under `alias.unwrap_or(column)` (`Null` for a
223/// column the producer did not emit), apply the optional-WHERE gate (the
224/// one [`where_clause_holds`] spelling: a non-boolean predicate is the
225/// typed rejection every other WHERE site raises, never a silent drop),
226/// and pad one null row when an OPTIONAL call produced nothing for the
227/// input row.
228pub(crate) fn compose_rows<'a>(
229 ctx: ExecCtx<'_>,
230 rows: Vec<Row>,
231 default_yields: &[&str],
232 yield_items: &YieldItems,
233 optional: bool,
234 where_clause: Option<&Expr>,
235 mut produce: impl FnMut(&Row) -> Result<Vec<Cow<'a, BTreeMap<String, Value>>>>,
236) -> Result<Vec<Row>> {
237 let ExecCtx { graph, params, .. } = ctx;
238 let yields: Vec<(String, Option<String>)> = yield_items.resolved_pairs(default_yields);
239 // The YIELD key rule (`alias`, else the column) resolved once; every
240 // loop below reads the same keys.
241 let keys: Vec<String> = yields
242 .iter()
243 .map(|(column, alias)| alias.clone().unwrap_or_else(|| column.clone()))
244 .collect();
245 let mut out = Vec::new();
246 for input in rows {
247 let mut produced = 0usize;
248 for values in produce(&input)? {
249 let mut row = input.clone();
250 for ((column, _), key) in yields.iter().zip(&keys) {
251 row.insert(
252 key.clone(),
253 values.get(column).cloned().unwrap_or(Value::Null),
254 );
255 }
256 if where_clause_holds(graph, &row, where_clause, params)? {
257 out.push(row);
258 produced += 1;
259 }
260 }
261 if produced == 0 && optional {
262 let mut row = input;
263 for key in &keys {
264 row.insert(key.clone(), Value::Null);
265 }
266 out.push(row);
267 }
268 }
269 Ok(out)
270}
271
272/// The entity kind a `db.index.vector.query*` procedure targets — the typed
273/// fact its name selected, so the dispatch is an exhaustive match instead
274/// of a bool re-encoded downstream.
275#[derive(Clone, Copy, Debug, PartialEq, Eq)]
276enum VectorEntity {
277 Nodes,
278 Relationships,
279}
280
281impl VectorEntity {
282 fn relationship(self) -> bool {
283 self == VectorEntity::Relationships
284 }
285}
286
287/// The one classification step of the `CALL` dispatch path
288/// ([`exec_call`]): which specialized executor owns the name — or `None`
289/// for the generic registry fallback. The `db.ontology.*` procedures
290/// (ADR-0121/ADR-0227) classify by the single [`OntologyProc::try_from`]
291/// (their executor's exhaustive dispatch enum); the vector and fulltext
292/// query procedures classify by the canonical signature registry — the
293/// exact, case-sensitive registered names (CIP-230), the same resolution
294/// the generic path's own built-in lookup below uses. This replaces the
295/// historical ad-hoc divert schemes (a registry scan plus a
296/// `starts_with` prefix plus `try_from` for the ontology divert, a
297/// lowercase literal match for the vector pair, a lowercase substring
298/// match for fulltext): no parallel name-matching scheme remains in the
299/// dispatch path.
300enum CallDivert {
301 /// One of the four `db.ontology.*` procedures, already classified.
302 Ontology(OntologyProc),
303 /// One of the two `db.index.vector.query*` procedures, with the entity
304 /// kind its name selects.
305 Vector(VectorEntity),
306 /// One of the two `db.index.fulltext.query*` procedures;
307 /// `kind` distinguishes `queryRelationships` from `queryNodes`.
308 FulltextQuery { kind: EntityKind },
309}
310
311/// The diverted-call classification as a predicate, for the producer-table
312/// completeness pin (test-only: no production path asks without also needing
313/// the variant).
314#[cfg(test)]
315pub(crate) fn is_diverted_call(name: &str) -> bool {
316 divert_call(name).is_some()
317}
318
319/// The one classification step: decide [`CallDivert`] for one `CALL` name,
320/// once, before the generic machinery.
321fn divert_call(name: &str) -> Option<CallDivert> {
322 if let Ok(proc) = OntologyProc::try_from(name) {
323 return Some(CallDivert::Ontology(proc));
324 }
325 // The registry lookup doubles as the classifier: only exact registered
326 // names divert, case-sensitively (CIP-230), exactly like the generic
327 // path's built-in resolution below.
328 match crate::procedure_registry::builtin_procedure_signature(name)?.name {
329 "db.index.vector.queryNodes" => Some(CallDivert::Vector(VectorEntity::Nodes)),
330 "db.index.vector.queryRelationships" => {
331 Some(CallDivert::Vector(VectorEntity::Relationships))
332 }
333 "db.index.fulltext.queryNodes" => Some(CallDivert::FulltextQuery {
334 kind: EntityKind::Node,
335 }),
336 "db.index.fulltext.queryRelationships" => Some(CallDivert::FulltextQuery {
337 kind: EntityKind::Relationship,
338 }),
339 _ => None,
340 }
341}
342
343/// The dispatcher's `CALL` arm, beside [`exec_call`] the executor it
344/// delegates to (stellar round 2, F-2-2): run the call, bind the scope
345/// names a void optional call over a zero-row driving table must expose
346/// as null, and answer the terminal void call's empty unit result.
347/// Returns the rows and, for a terminal void call, its statement
348/// result; the dispatcher consumes both.
349#[allow(clippy::too_many_arguments)]
350pub(crate) fn exec_call_clause(
351 ctx: ExecCtx<'_>,
352 clauses: &[Clause],
353 index: usize,
354 rows: Vec<Row>,
355 name: &SmallName,
356 source: &CallArgs,
357 yield_items: &YieldItems,
358 optional: bool,
359 where_clause: Option<&Expr>,
360) -> Result<(Vec<Row>, Option<QueryResult>)> {
361 let was_empty = rows.is_empty();
362 // Text render: the procedure dispatcher matches on name text
363 // (String vocabulary), once per clause.
364 let call_name = name.to_string();
365 let (mut rows, yields_unit) = exec_call(
366 ctx,
367 rows,
368 CallSpec {
369 name: &call_name,
370 source,
371 yield_items,
372 optional,
373 where_clause,
374 },
375 )?;
376 // A void optional call over a zero-row driving table yields
377 // one unit row (CIP-159 [12]); Neo4j reads every variable
378 // in scope as null on it, so bind the scope names
379 // explicitly (ADR-0335) instead of leaving a following
380 // projection to read an unbound reference.
381 if was_empty && rows.len() == 1 && rows[0].is_empty() {
382 for name in star_scope_names(&clauses[..index]) {
383 rows[0].insert(name, Value::Null);
384 }
385 }
386 // A terminal void call yields an empty unit result (CIP-159):
387 // the call path reported the fact on the resolution it
388 // already made.
389 let result = (index + 1 == clauses.len() && yields_unit)
390 .then(|| QueryResult::intermediate(Vec::new(), Vec::new(), QueryStats::default()));
391 Ok((rows, result))
392}
393
394pub(crate) fn exec_call(
395 ctx: ExecCtx<'_>,
396 rows: Vec<Row>,
397 call: CallSpec<'_>,
398) -> Result<(Vec<Row>, bool)> {
399 // ONE classification step decides divert-or-generic once. The
400 // `db.ontology.*` divert runs the same runtime contract (passing
401 // mode, arity — `CallSpec::check_registry_contract`) the generic
402 // path runs below, at this same site, before handing the call to
403 // its executor; the vector and fulltext executors take their
404 // contract through `CallSpec::check_positional_contract`, whose
405 // positional form their scans read. Everything else falls to the
406 // generic registry machinery below.
407 // The unit fact is the registry's: every diverted name is a registered
408 // signature, so the call path reports `is_void()` rather than re-deriving
409 // it per arm.
410 let yields_unit = crate::exec::procedure_rows::executable_signature(call.name)
411 .is_some_and(ProcSignature::is_void);
412 match divert_call(call.name) {
413 Some(CallDivert::Ontology(proc)) => {
414 call.check_registry_contract()?;
415 exec_ontology_call(ctx, rows, call, proc).map(|rows| (rows, yields_unit))
416 }
417 Some(CallDivert::Vector(entity)) => {
418 exec_vector_query_call(ctx, rows, entity, call).map(|rows| (rows, yields_unit))
419 }
420 Some(CallDivert::FulltextQuery { kind }) => {
421 exec_fulltext_query_call(ctx, rows, kind, call).map(|rows| (rows, yields_unit))
422 }
423 None => exec_registry_call(ctx, rows, call),
424 }
425}
426
427/// Which rows one resolved call answers: the rows it already has (a
428/// registered procedure's stored rows or a no-argument built-in's
429/// once-produced rows), or a producing signature whose rows are a function of
430/// each row's bound arguments.
431enum CallRows<'a> {
432 Rows(Cow<'a, [BTreeMap<String, Value>]>),
433 PerRow(&'static ProcSignature),
434}
435
436/// One `CALL`'s resolved shape, from the one resolution: the metadata its
437/// arguments bind against, its minimum arity, whether it yields columns, and
438/// where its rows come from. The call path reads this and never re-matches
439/// the target.
440struct ResolvedCall<'a> {
441 metadata: Cow<'a, Procedure>,
442 required_args: usize,
443 yields_unit: bool,
444 rows: CallRows<'a>,
445}
446
447/// The generic registry path a non-diverted call takes: one resolution into a
448/// [`CallTarget`], the passing-mode and arity contract, per-row argument
449/// binding and type check, row matching, composition, and the void-procedure
450/// unit row. One unit, so the classifier above stays a classifier.
451fn exec_registry_call(
452 ctx: ExecCtx<'_>,
453 rows: Vec<Row>,
454 call: CallSpec<'_>,
455) -> Result<(Vec<Row>, bool)> {
456 let ExecCtx {
457 graph, principal, ..
458 } = ctx;
459 let CallSpec {
460 name,
461 source,
462 yield_items,
463 optional,
464 where_clause,
465 } = call;
466 // One resolution decides registered-vs-builtin and carries everything
467 // the call needs: metadata, arity, the unit fact and the row source. A
468 // void call produces no rows at all, so nothing is produced to be
469 // discarded.
470 let registered = graph.procedure(name);
471 let resolved = match ®istered {
472 Some(procedure) => ResolvedCall {
473 yields_unit: procedure.yield_names.is_empty() && procedure.rows.is_empty(),
474 metadata: Cow::Borrowed(procedure),
475 required_args: procedure.arg_names.len(),
476 rows: CallRows::Rows(Cow::Borrowed(procedure.rows.as_slice())),
477 },
478 None => {
479 let signature =
480 executable_signature(name).ok_or_else(|| Error::procedure_not_found(name))?;
481 let rows = if signature.is_void() {
482 CallRows::Rows(Cow::Borrowed(&[]))
483 } else if signature.args.is_empty() {
484 CallRows::Rows(Cow::Owned(builtin_procedure_rows(
485 graph,
486 signature,
487 principal,
488 &BTreeMap::new(),
489 )?))
490 } else {
491 CallRows::PerRow(signature)
492 };
493 ResolvedCall {
494 yields_unit: signature.is_void(),
495 metadata: Cow::Owned(procedure_metadata(signature)),
496 required_args: signature.required_args(),
497 rows,
498 }
499 }
500 };
501 let ResolvedCall {
502 metadata,
503 required_args,
504 yields_unit,
505 rows: row_source,
506 } = resolved;
507 // Same rule on the unit-call path (LABS-389): required_args already
508 // folds the builtin/registered split, so the guard reads it instead
509 // of any-args. The one contract check every dispatch path reads
510 // (CallSpec::check_contract), over this resolution's own pair: the
511 // passing-mode backstop plus the explicit list's arity — the
512 // paren-less form carries no positional arity here, its arguments
513 // resolving by name in the binder below.
514 call.check_contract(required_args, metadata.arg_names.len())?;
515 if yields_unit && void_optional_unit_row(rows.is_empty(), optional) {
516 return Ok((vec![Row::new()], true));
517 }
518 let binding = CallBinding {
519 name,
520 source,
521 metadata: &metadata,
522 required_args,
523 ctx,
524 };
525 let mut out = Vec::new();
526 // One binding pass over the driving rows: a void call binds and
527 // type-checks each row's arguments too, it just produces nothing.
528 for row in &rows {
529 let call_args = binding.bind_row(row)?;
530 if yields_unit {
531 continue;
532 }
533 // Rows come from the resolved target: a registered procedure's are
534 // fixed at registration, a no-argument built-in's were produced once
535 // above, and any other built-in's are a function of this row's bound
536 // arguments (a null `db.schema.visualization` options map selects
537 // nothing at all; a `db.stats.retrieve` section names the section it
538 // serves).
539 let proc_rows: Cow<'_, [BTreeMap<String, Value>]> = match &row_source {
540 CallRows::Rows(rows) => Cow::Borrowed(rows.as_ref()),
541 CallRows::PerRow(signature) => Cow::Owned(builtin_procedure_rows(
542 graph, signature, principal, &call_args,
543 )?),
544 };
545 let matched: Vec<_> = proc_rows
546 .iter()
547 .filter(|pr| {
548 metadata
549 .arg_names
550 .iter()
551 .all(|n| match (pr.get(n), call_args.get(n)) {
552 (Some(a), Some(b)) => call_args_match(a, b),
553 (None, _) => true,
554 _ => false,
555 })
556 })
557 .collect();
558 if matched.is_empty() && metadata.yield_names.is_empty() {
559 out.push(row.clone());
560 continue;
561 }
562 let default_yields: Vec<&str> = metadata.yield_names.iter().map(String::as_str).collect();
563 out.extend(compose_rows(
564 ctx,
565 vec![row.clone()],
566 &default_yields,
567 yield_items,
568 optional,
569 where_clause,
570 // The matched rows are BORROWED, not cloned: compose_rows
571 // clones only the yielded cells it inserts, so a wide
572 // procedure row costs one cell per yielded column — never a
573 // full-row deep clone per input row.
574 |_| Ok(matched.iter().map(|pr| Cow::Borrowed(*pr)).collect()),
575 )?);
576 }
577 Ok((if yields_unit { rows } else { out }, yields_unit))
578}
579
580/// One resolved CALL's binding context: the facts every per-row bind needs,
581/// carried once instead of as nine positional parameters.
582struct CallBinding<'a> {
583 name: &'a str,
584 source: &'a CallArgs,
585 metadata: &'a Procedure,
586 required_args: usize,
587 ctx: ExecCtx<'a>,
588}
589
590impl CallBinding<'_> {
591 /// Bind one driving row's arguments and type-check them against the
592 /// resolved metadata — the one binding policy the row loop and the
593 /// resolved call share, so a void procedure's arguments are validated
594 /// exactly like a row-answering one's.
595 fn bind_row(&self, row: &Row) -> Result<BTreeMap<String, Value>> {
596 // One declared type per declared argument: `procedure_metadata` and
597 // registration build the two lists together, so a shorter type list
598 // is an engine bug, not a per-argument absence.
599 if self.metadata.arg_types.len() != self.metadata.arg_names.len() {
600 return Err(Error::internal(format!(
601 "procedure '{}' declares {} arguments but {} types",
602 self.name,
603 self.metadata.arg_names.len(),
604 self.metadata.arg_types.len()
605 )));
606 }
607 if let CallArgs::Implicit = self.source {
608 // Only parameters without a default are mandatory; defaulted
609 // built-in parameters (e.g. `db.awaitIndexes`'s
610 // `timeOutSeconds`) may be omitted.
611 let missing_required = self
612 .metadata
613 .arg_names
614 .iter()
615 .take(self.required_args)
616 .any(|n| !self.ctx.params.contains_key(n) && !row.contains_key(n));
617 if missing_required {
618 return Err(Error::syntax(format!(
619 "MissingParameter: implicit args for {}",
620 self.name
621 )));
622 }
623 }
624 let mut call_args = BTreeMap::new();
625 for (index, (n, ty)) in self
626 .metadata
627 .arg_names
628 .iter()
629 .zip(self.metadata.arg_types.iter())
630 .enumerate()
631 {
632 let Some(value) = call_arg_value(&self.ctx, row, self.source, index, n)? else {
633 // A defaulted implicit argument may legitimately be absent.
634 continue;
635 };
636 if !value_matches_proc_type(&value, ty) {
637 return Err(Error::syntax(format!(
638 "InvalidArgumentType: {} argument `{n}` expects {ty}",
639 self.name
640 )));
641 }
642 call_args.insert(n.clone(), value);
643 }
644 Ok(call_args)
645 }
646}
647
648/// Resolve one declared CALL argument through the call's one passing-mode
649/// value: the explicit positional expression evaluated against the driving
650/// row, or the implicit parameter/row-column value. The one per-argument
651/// resolver the generic binder and the `db.ontology.*` readers share, so
652/// the policy is spelled once.
653pub(crate) fn call_arg_value(
654 ctx: &ExecCtx<'_>,
655 row: &Row,
656 source: &CallArgs,
657 index: usize,
658 arg_name: &str,
659) -> Result<Option<Value>> {
660 match source {
661 CallArgs::Explicit(args) => args
662 .get(index)
663 .map(|expr| eval(ctx.graph, row, expr, ctx.params))
664 .transpose(),
665 CallArgs::Implicit => Ok(ctx
666 .params
667 .get(arg_name)
668 .cloned()
669 .or_else(|| row.get(arg_name).cloned())),
670 }
671}
672
673/// The one fulltext scan for both `db.index.fulltext.query*` procedures:
674/// `kind` selects the entity kind (relationship indexes match on
675/// relationship types, node indexes on labels) and the yielded column name.
676pub(crate) fn exec_fulltext_query_call(
677 ctx: ExecCtx<'_>,
678 rows: Vec<Row>,
679 kind: EntityKind,
680 call: CallSpec<'_>,
681) -> Result<Vec<Row>> {
682 let CallSpec {
683 yield_items,
684 optional,
685 where_clause,
686 ..
687 } = call;
688 let ExecCtx { graph, params, .. } = ctx;
689 // The one contract check every dispatch path reads, over the name's
690 // canonical registry signature — the passing-mode backstop plus the
691 // arity, in the positional form this scan reads (a paren-less call
692 // passes no list, so it answers the arity rejection exactly like a
693 // short explicit one).
694 let args = call.check_positional_contract()?;
695 // The entity column is the divert's classification; the score column
696 // is shared by both entity variants, so the table is one choice plus
697 // one literal.
698 let entity_column = match kind {
699 EntityKind::Node => "node",
700 EntityKind::Relationship => "relationship",
701 };
702 let score_key = "score";
703 let columns = [entity_column, score_key];
704 // One corpus per index for the whole call, not one per input row.
705 let corpora = fulltext::CorpusMemo::default();
706 compose_rows(
707 ctx,
708 rows,
709 &columns,
710 yield_items,
711 optional,
712 where_clause,
713 |input| {
714 let index_name = eval(graph, input, &args[0], params)?
715 .as_string()
716 .ok_or_else(|| Error::invalid_argument_type("indexName must be STRING"))?
717 .to_string();
718 let query = eval(graph, input, &args[1], params)?
719 .as_string()
720 .ok_or_else(|| Error::invalid_argument_type("query must be STRING"))?
721 .to_string();
722 // The shared SEARCH index resolution (the vector procedure's
723 // one spelling): a missing or non-fulltext index is that
724 // helper's typed error. Only the entity-kind disagreement is
725 // this procedure's own — `queryNodes` on a relationship index
726 // (or the reverse) has no scan to run.
727 let (detail, options) =
728 resolve_search_index(graph, &index_name, crate::redo::IndexKindSpec::Fulltext)?;
729 if EntityKind::from_relationship_flag(detail.relationship) != kind {
730 return Err(Error::execution(
731 "WrongIndexType: fulltext index entity type mismatch",
732 ));
733 }
734 // The one CIP-225 scan: the Lucene-style query parser (terms
735 // OR'd, `AND`/`OR`/`NOT`, `property:term` field filters) and the
736 // live-fitted BM25 score, ranked best-first, no window.
737 let analyzers = fulltext::Analyzers::new(
738 crate::exec::ddl_options::index_analyzer(&options, &index_name)?,
739 None,
740 );
741 let produced = fulltext::search_all(&corpora, graph, &detail, &query, analyzers)?
742 .into_iter()
743 .map(|(id, score)| {
744 Cow::Owned(BTreeMap::from([
745 (
746 entity_column.to_string(),
747 materialize_candidate(graph, kind, id),
748 ),
749 (score_key.to_string(), Value::Float(score)),
750 ]))
751 })
752 .collect();
753 Ok(produced)
754 },
755 )
756}
757
758fn exec_vector_query_call(
759 ctx: ExecCtx<'_>,
760 rows: Vec<Row>,
761 entity: VectorEntity,
762 call: CallSpec<'_>,
763) -> Result<Vec<Row>> {
764 let relationship = entity.relationship();
765 let CallSpec {
766 yield_items,
767 optional,
768 where_clause,
769 ..
770 } = call;
771 let ExecCtx { graph, params, .. } = ctx;
772 // The one contract check every dispatch path reads, over the name's
773 // canonical registry signature — the passing-mode backstop plus the
774 // arity, in the positional form this scan reads (a paren-less call
775 // passes no list, so it answers the arity rejection exactly like a
776 // short explicit one).
777 let args = call.check_positional_contract()?;
778 // The divert already classified the entity kind (`relationship` is
779 // `queryRelationships` vs `queryNodes`); no name re-matching here.
780 let entity_column = if relationship { "relationship" } else { "node" };
781 compose_rows(
782 ctx,
783 rows,
784 &[entity_column, "score"],
785 yield_items,
786 optional,
787 where_clause,
788 |input| {
789 let index_name = eval(graph, input, &args[0], params)?
790 .as_string()
791 .ok_or_else(|| Error::invalid_argument_type("indexName must be STRING"))?
792 .to_string();
793 let limit = match eval(graph, input, &args[1], params)? {
794 Value::Int(value) if (1..=i32::MAX as i64).contains(&value) => value as usize,
795 _ => return Err(Error::ty(
796 "InvalidArgumentValue: numberOfNearestNeighbours must be a positive INTEGER",
797 )),
798 };
799 let query = eval(graph, input, &args[2], params)?;
800 let Some(query) = vector_operand(&query)? else {
801 return Ok(Vec::new());
802 };
803 let (index_kind, candidates) = vector_index_candidates(
804 ctx,
805 &index_name,
806 &query,
807 0,
808 limit,
809 VectorSearchFilter {
810 filters: &[],
811 input,
812 },
813 )?;
814 if index_kind.is_relationship() != relationship {
815 return Err(Error::execution(
816 "WrongIndexType: vector index entity type mismatch",
817 ));
818 }
819 let mut produced = Vec::new();
820 for (entity, score) in candidates {
821 // Both entity spellings map to the candidate (the
822 // historical cell match keyed `"node" | "relationship"`),
823 // so an explicit YIELD of either sees it.
824 produced.push(BTreeMap::from([
825 ("node".to_string(), entity.clone()),
826 ("relationship".to_string(), entity.clone()),
827 ("score".to_string(), Value::Float(score)),
828 ]));
829 }
830 Ok(produced.into_iter().map(Cow::Owned).collect())
831 },
832 )
833}
834
835#[cfg(test)]
836mod type_vocabulary_tests {
837 use super::value_matches_proc_type;
838 use relate_core::Value;
839
840 /// ADR-0463 round 6: the list spelling is exactly `LIST` or `LIST<…>`;
841 /// a bare prefix match would silently accept `LISTS`/`LISTING` as any
842 /// list, re-opening the fail-closed vocabulary.
843 #[test]
844 fn list_type_accepts_only_list_or_list_generic() {
845 let list = Value::List(Vec::new().into());
846 assert!(value_matches_proc_type(&list, "LIST"));
847 assert!(value_matches_proc_type(&list, "LIST<FLOAT>"));
848 assert!(value_matches_proc_type(&list, "list<string>"));
849 assert!(!value_matches_proc_type(&list, "LISTS"));
850 assert!(!value_matches_proc_type(&list, "LISTING"));
851 assert!(!value_matches_proc_type(&Value::Int(1), "LISTS"));
852 }
853}
854
855#[cfg(test)]
856mod row_provenance_tests {
857 use std::collections::BTreeMap;
858
859 use crate::exec::test_support::{
860 exec_autocommit, exec_cypher, try_exec_cypher, try_exec_cypher_params,
861 };
862 use crate::graph::Graph;
863 use relate_core::Value;
864
865 /// The diverted scan calls read their arguments positionally, so the
866 /// one contract check every dispatch path reads (stellar round 2,
867 /// F-2-26/F-2-43) states the paren-less form's rejection by its
868 /// form: with a YIELD it is the passing-mode violation — never a
869 /// misleading arity count — and standalone it is the arity
870 /// rejection over the empty list the grammar passes.
871 #[test]
872 fn the_diverted_scan_contract_rejects_paren_less_calls_by_their_form() {
873 let graph = Graph::default();
874 let in_query = try_exec_cypher(&graph, "CALL db.index.vector.queryNodes YIELD node")
875 .err()
876 .expect("an in-query paren-less vector call is the passing-mode rejection");
877 assert!(
878 in_query.to_string().contains("InvalidArgumentPassingMode"),
879 "{in_query}"
880 );
881 let standalone = try_exec_cypher(&graph, "CALL db.index.vector.queryNodes")
882 .err()
883 .expect("a paren-less vector call passes no positional list");
884 let text = standalone.to_string();
885 assert!(
886 text.contains("InvalidNumberOfArguments")
887 && text.contains("db.index.vector.queryNodes expected 3, got 0"),
888 "{text}"
889 );
890 }
891
892 /// A `CALL`'s `YIELD … WHERE` is a predicate position: a runtime
893 /// non-boolean (a parameter bound to an integer) is the typed
894 /// `requires a boolean` rejection every other optional-WHERE site
895 /// raises through the one `where_clause_holds` gate — never a silent
896 /// row drop (the composer once hand-spelled the truthy check).
897 #[test]
898 fn a_call_yield_where_with_a_non_boolean_parameter_is_the_typed_rejection() {
899 let graph = Graph::default();
900 exec_autocommit(&graph, "CREATE (:User), (:Admin)").expect("the fixture's CREATE succeeds");
901 let params: BTreeMap<String, Value> =
902 [("flag".to_string(), Value::Int(7))].into_iter().collect();
903 let error = try_exec_cypher_params(
904 &graph,
905 "CALL db.labels() YIELD label WHERE $flag RETURN label",
906 ¶ms,
907 )
908 .err()
909 .expect("a non-boolean CALL YIELD WHERE predicate must be rejected");
910 let text = error.to_string();
911 assert!(
912 text.contains("InvalidArgumentType") && text.contains("requires a boolean"),
913 "{text}"
914 );
915 }
916
917 /// A no-argument built-in's rows are produced once for the call and
918 /// answered by every driving row — two driving rows times two labels,
919 /// never one production that only the first row sees.
920 #[test]
921 fn a_no_argument_builtin_answers_its_rows_for_every_driving_row() {
922 let graph = Graph::default();
923 exec_autocommit(&graph, "CREATE (:User), (:Admin)").expect("the fixture's CREATE succeeds");
924
925 let result = exec_cypher(
926 &graph,
927 "UNWIND [1, 2] AS i CALL db.labels() YIELD label \
928 RETURN i, label ORDER BY i, label",
929 );
930 let string = |value: &str| Value::String(value.into());
931 assert_eq!(
932 result.rows,
933 vec![
934 vec![Value::Int(1), string("Admin")],
935 vec![Value::Int(1), string("User")],
936 vec![Value::Int(2), string("Admin")],
937 vec![Value::Int(2), string("User")],
938 ]
939 );
940 }
941
942 /// A built-in whose producer reads its arguments produces them under
943 /// every driving row's own binding: `db.stats.retrieve` is served the
944 /// section each row carries, never an empty argument map.
945 #[test]
946 fn an_argument_taking_builtin_produces_rows_from_each_rows_bindings() {
947 let graph = Graph::default();
948
949 let result = exec_cypher(
950 &graph,
951 "UNWIND [1, 2] AS i WITH i, 'GRAPH COUNTS' AS wanted \
952 CALL db.stats.retrieve(wanted) YIELD section RETURN i, section",
953 );
954 assert_eq!(
955 result.rows,
956 vec![
957 vec![Value::Int(1), Value::String("GRAPH COUNTS".into())],
958 vec![Value::Int(2), Value::String("GRAPH COUNTS".into())],
959 ]
960 );
961 }
962}