relate_executor/procedure_registry.rs
1//! Canonical built-in procedure signature registry: the single table of
2//! argument/return-column names and types for every procedure the engine
3//! executes or lists.
4//!
5//! Five consumers share this table so they cannot drift apart (e.g. the
6//! vector `query` argument typed `ANY` in one place and `LIST<FLOAT>` in
7//! another):
8//!
9//! - `exec::procedure_rows::builtin_procedure_rows` — the executor's `CALL`
10//! dispatch (arg names/types, yield columns, arity, and the rows);
11//! - `relate::Database`'s compile-time `validate_calls` (same shapes);
12//! - `relate`'s namespace write classification (`writes`, ADR-0116 §4);
13//! - `show_catalog::procedure_catalog_rows` — the `SHOW PROCEDURES` catalog
14//! (CIP-84/CIP-113/CIP-157 display, which additionally reads the
15//! description/mode/deprecation fields);
16//! - `procedure_gate::procedure_preview_feature` — the preview-feature
17//! mapping of the `db.ontology.*` family (ADR-0378).
18
19use relate_core::Value;
20
21use crate::catalog_meta::{DeprecatedBy, ProcArgMeta};
22
23/// Which row producer a row-declaring executable signature carries: the
24/// registry owns the fact, so a signature that declares return columns but
25/// names no producer cannot be written without the table saying so, and the
26/// producer table cannot drift into a second name-keyed list.
27///
28/// The variants are listed in the same order as their arms in the `produce`
29/// dispatch (`exec::procedure_rows`); keeping the two in step is a
30/// readability convention, not an enforced invariant.
31///
32/// Crate-internal: no reader outside this crate names a producer, matching
33/// `args`/`returns`.
34#[derive(Clone, Copy, Debug)]
35pub(crate) enum RowProducer {
36 TxGetMetaData,
37 DbmsComponents,
38 DbPing,
39 DbLabels,
40 DbRelationshipTypes,
41 DbPropertyKeys,
42 DbInfo,
43 DbmsInfo,
44 DbmsShowCurrentUser,
45 DbmsConfig,
46 DbmsLicenseAgreementDetails,
47 DbmsListCapabilities,
48 FulltextAnalyzers,
49 DbStatsRetrieve,
50 SchemaNodeTypeProperties,
51 SchemaRelTypeProperties,
52 SchemaVisualization,
53}
54
55/// Static signature and catalog metadata of a built-in procedure.
56pub struct ProcSignature {
57 pub name: &'static str,
58 pub description: &'static str,
59 pub mode: &'static str,
60 pub works_on_system: bool,
61 pub admin: bool,
62 /// Formal parameters. Required parameters come first; a parameter with
63 /// a `default` may be omitted by the caller (CIP-113's
64 /// `name = default :: type` rendering). Crate-internal (the parameter
65 /// type is); a cross-crate caller reads [`Self::parameters`].
66 pub(crate) args: &'static [ProcArgMeta],
67 /// Return columns (`YIELD` names/types). Crate-internal; a cross-crate
68 /// caller reads [`Self::return_columns`].
69 pub(crate) returns: &'static [ProcArgMeta],
70 /// The replacement when the procedure is deprecated (CIP-157's
71 /// `deprecatedBy`); `None` means not deprecated. One fact, so a bool and
72 /// its replacement cannot disagree.
73 pub deprecated_by: Option<DeprecatedBy>,
74 /// True when `CALL` can actually execute it (as opposed to a
75 /// catalog-only entry pinned by CIP-84/CIP-113/CIP-157 scenarios that no
76 /// scenario calls).
77 pub executable: bool,
78 /// True when `SHOW PROCEDURES` lists it.
79 pub listed: bool,
80 /// The row producer a row-declaring executable signature carries; `None`
81 /// for a void signature, a catalog-only entry, a diverted procedure
82 /// (whose `CALL` path is a dedicated executor — see `divert_call`) and
83 /// a compat callable (ADR-0699: the query front-end rewrites its `CALL`
84 /// into a Cypher body before lowering — `relate_front`'s
85 /// `compat_callables` table owns the membership, and the dispatch
86 /// declines it by name). One fact with the return columns: a
87 /// row-declaring signature answers through exactly one of the three —
88 /// a producer arm here, a diverted call path, or the front-end
89 /// rewrite that lowers it away before the executor ever sees it.
90 pub(crate) rows: Option<RowProducer>,
91 /// True when a `CALL` mutates the graph or catalog (ADR-0116 §4) — the
92 /// write classification `relate`'s namespace rules read, so there is
93 /// one table (`mode` does not encode this: DBMS-mode entries such as
94 /// `dbms.components` and `tx.setMetaData` are not graph/catalog writes).
95 pub writes: bool,
96 /// True when the procedure's commit is a store-level commit of its own
97 /// (ADR-0120 §3) — the `db.ontology.set` / `db.ontology.drop` store ops,
98 /// which push a store-level redo and require the implicit-only /
99 /// no-mixed-writes gates; the in-overlay `db.ontology.apply` write is
100 /// not one. The store-op classification reads this table the same way
101 /// the write classification reads `writes`.
102 pub store_level: bool,
103}
104
105impl ProcSignature {
106 /// The common entry: a listed, executable read procedure with no
107 /// description, catalog flags or deprecation. The builders below name
108 /// only what a row changes from it, so the table states each entry's
109 /// deviations instead of restating ten fields per row.
110 pub(crate) const fn read(name: &'static str) -> Self {
111 Self {
112 name,
113 description: "",
114 mode: "READ",
115 works_on_system: false,
116 admin: false,
117 args: &[],
118 returns: &[],
119 deprecated_by: None,
120 executable: true,
121 listed: true,
122 writes: false,
123 store_level: false,
124 rows: None,
125 }
126 }
127
128 /// A listed procedure whose mode is `"DBMS"`. The system-database
129 /// capability is a separate fact — the corpus lists `tx.setMetaData` as
130 /// DBMS-mode but not system-database-capable (ADR-0497 §6) — so each
131 /// entry states [`Self::works_on_system`] itself.
132 pub(crate) const fn dbms(name: &'static str) -> Self {
133 let mut sig = Self::read(name);
134 sig.mode = "DBMS";
135 sig
136 }
137
138 /// A listed procedure whose mode is `"WRITE"`. The `writes` flag is a
139 /// separate fact: a catalog-only entry carries the mode without being
140 /// callable, so it can mutate nothing.
141 pub(crate) const fn write(name: &'static str) -> Self {
142 let mut sig = Self::read(name);
143 sig.mode = "WRITE";
144 sig
145 }
146
147 /// A listed procedure whose mode is `"SCHEMA"`. The [`Self::writes`]
148 /// flag is a separate fact, as on [`Self::write`]: a schema-mode
149 /// procedure that mutates the store still routes its statements to the
150 /// write path through `writes`, while the mode itself is only the
151 /// catalog rendering.
152 pub(crate) const fn schema(name: &'static str) -> Self {
153 let mut sig = Self::read(name);
154 sig.mode = "SCHEMA";
155 sig
156 }
157
158 /// The row producer this signature's rows come from.
159 pub(crate) const fn rows(mut self, rows: RowProducer) -> Self {
160 self.rows = Some(rows);
161 self
162 }
163
164 /// The procedure works on the system database.
165 pub(crate) const fn works_on_system(mut self) -> Self {
166 self.works_on_system = true;
167 self
168 }
169
170 /// A description for the catalog row.
171 pub(crate) const fn described(mut self, description: &'static str) -> Self {
172 self.description = description;
173 self
174 }
175
176 /// The procedure requires admin privileges.
177 pub(crate) const fn admin(mut self) -> Self {
178 self.admin = true;
179 self
180 }
181
182 /// A `CALL` mutates the graph or catalog (ADR-0116 §4).
183 pub(crate) const fn writes(mut self) -> Self {
184 self.writes = true;
185 self
186 }
187
188 /// The procedure's commit is a store-level commit of its own (ADR-0120 §3).
189 pub(crate) const fn store_level(mut self) -> Self {
190 self.store_level = true;
191 self
192 }
193
194 /// The procedure's formal parameters.
195 pub(crate) const fn args(mut self, args: &'static [ProcArgMeta]) -> Self {
196 self.args = args;
197 self
198 }
199
200 /// The procedure's return columns.
201 pub(crate) const fn returns(mut self, returns: &'static [ProcArgMeta]) -> Self {
202 self.returns = returns;
203 self
204 }
205
206 /// The replacement when the procedure is deprecated (CIP-157).
207 pub(crate) const fn deprecated_by(mut self, by: DeprecatedBy) -> Self {
208 self.deprecated_by = Some(by);
209 self
210 }
211
212 /// Whether `CALL` can actually execute it.
213 pub(crate) const fn executable(mut self, executable: bool) -> Self {
214 self.executable = executable;
215 self
216 }
217
218 /// Whether `SHOW PROCEDURES` lists it.
219 pub(crate) const fn listed(mut self, listed: bool) -> Self {
220 self.listed = listed;
221 self
222 }
223}
224
225impl ProcSignature {
226 /// Number of leading parameters without a default — the minimum arity a
227 /// `CALL` may pass. (`args` lists required parameters first.)
228 pub fn required_args(&self) -> usize {
229 self.args.iter().take_while(|a| a.default.is_none()).count()
230 }
231
232 /// The formal parameters as `(name, declared type)` pairs, required
233 /// parameters first — a caller outside this crate's view of `args`
234 /// (`ProcArgMeta` is crate-internal). The compile-time `CALL`
235 /// validation reads this.
236 pub fn parameters(&self) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
237 self.args.iter().map(|arg| (arg.name, arg.type_str))
238 }
239
240 /// The `YIELD` column names, in signature order — a caller outside this
241 /// crate's view of `returns`.
242 pub fn return_columns(&self) -> impl Iterator<Item = &'static str> + '_ {
243 self.returns.iter().map(|ret| ret.name)
244 }
245
246 /// Whether the procedure produces no rows — a unit procedure such as
247 /// `tx.setMetaData`, `db.createLabel` or `db.awaitIndexes` declares no
248 /// return columns. The one void fact: the clause engine's terminal-call
249 /// check and the row-producer dispatch both read it instead of each
250 /// re-deriving it from `returns`.
251 pub(crate) fn is_void(&self) -> bool {
252 self.returns.is_empty()
253 }
254}
255
256mod signatures;
257
258pub use signatures::BUILTIN_PROCEDURE_SIGNATURES;
259
260/// Looks up a built-in procedure signature by name, case-sensitively.
261/// Casing sensitivity: built-in *function* names are
262/// case-insensitive, but built-in *procedure* names are case-sensitive --
263/// `CALL DB.LABELS()` is an UnknownProcedure error, only the exact declared
264/// casing (`CALL db.labels()`) resolves. The validator must agree.
265pub fn builtin_procedure_signature(name: &str) -> Option<&'static ProcSignature> {
266 BUILTIN_PROCEDURE_SIGNATURES
267 .iter()
268 .find(|sig| sig.name == name)
269}
270
271/// Whether the procedure behind `name` declares no return columns — the one
272/// void-procedure fact, so the `CALL` contract validator and the
273/// redundant-`OPTIONAL` notification detector cannot drift.
274///
275/// `registered` is the caller's own lookup of a user-registered procedure,
276/// which shadows the built-in: it answers from its `yield_names`, the
277/// built-in from the one signature table. A name that is neither is not a
278/// procedure, and is not void.
279pub fn is_void_procedure(registered: Option<&crate::graph::Procedure>, name: &str) -> bool {
280 if let Some(procedure) = registered {
281 return procedure.yield_names.is_empty();
282 }
283 builtin_procedure_signature(name).is_some_and(ProcSignature::is_void)
284}
285
286/// Whether a value satisfies a procedure argument type string (`STRING`,
287/// `INTEGER`, `LIST<FLOAT>`, …). `ANY`, an empty type, a nullable `?`
288/// suffix, and a null value match everything; the accepted type vocabulary
289/// is explicit and fails closed, so an unknown (typo'd or unmodelled) type
290/// name matches nothing. The precise element-type check of a list happens
291/// in the procedure body itself. The canonical home is here, beside the
292/// type strings this registry declares — the facade's compile-time
293/// `validate_calls` and the executor's per-row binder read the one
294/// spelling, so the two cannot drift.
295pub fn value_matches_proc_type(v: &Value, ty: &str) -> bool {
296 matches_normalized_type(v, &normalize_proc_type(ty))
297}
298
299/// One signature's declared type string in the vocabulary's own form —
300/// trimmed, `?`-stripped, uppercased. The binder normalizes its binding's
301/// declared types once at construction, so the per-row check never pays
302/// this again.
303pub(crate) fn normalize_proc_type(ty: &str) -> String {
304 ty.trim().trim_end_matches('?').trim().to_ascii_uppercase()
305}
306
307/// The vocabulary match over an already-normalized type string (a
308/// signature may declare several admissible types — `BOOLEAN|MAP`, the
309/// Cypher 25 and legacy forms of one argument — each alternative already
310/// normalized with the whole).
311pub(crate) fn matches_normalized_type(v: &Value, ty: &str) -> bool {
312 if v.is_null() || ty.is_empty() || ty == "ANY" {
313 return true;
314 }
315 if ty.contains('|') {
316 // Each alternative trims on its own: a union spelled with spaces
317 // (`STRING | INTEGER`) normalizes as a whole, so the split arms
318 // can carry leading or trailing blanks.
319 return ty
320 .split('|')
321 .any(|alternative| matches_normalized_type(v, alternative.trim()));
322 }
323 // The accepted type vocabulary is explicit and fails closed: an unknown
324 // (typo'd or unmodelled) name does not silently disable checking.
325 // Generic lists (`LIST<FLOAT>`, `LIST<NODE>`, …) share the list check.
326 if ty == "LIST" || ty.starts_with("LIST<") {
327 return matches!(v, Value::List(_));
328 }
329 match ty {
330 "STRING" => matches!(v, Value::String(_)),
331 "INTEGER" | "INT" => matches!(v, Value::Int(_)),
332 "FLOAT" => matches!(v, Value::Float(_) | Value::Int(_)),
333 "NUMBER" => matches!(v, Value::Int(_) | Value::Float(_)),
334 "BOOLEAN" | "BOOL" => matches!(v, Value::Bool(_)),
335 "MAP" => matches!(v, Value::Map(_)),
336 "NODE" => matches!(v, Value::Node(_)),
337 "RELATIONSHIP" | "REL" => matches!(v, Value::Relationship(_)),
338 "PATH" => matches!(v, Value::Path(_)),
339 "BYTES" => matches!(v, Value::Bytes(_)),
340 "DATE" | "DATETIME" | "LOCAL DATETIME" | "LOCALDATETIME" | "TIME" | "LOCAL TIME"
341 | "LOCALTIME" | "DURATION" => matches!(v, Value::Temporal(_)),
342 "POINT" => matches!(v, Value::Point(_)),
343 "UUID" => matches!(v, Value::Uuid(_)),
344 "VECTOR" => matches!(v, Value::Vector { .. }),
345 _ => false,
346 }
347}
348
349/// Whether `name` names one of the `db.ontology.*` procedures (ADR-0121 as
350/// amended by ADR-0227). Derived from the one table so the facade's
351/// compile-time gates (no-mixed-writes, transaction-mixing, target
352/// namespace) and the executor's `CALL` dispatch cannot drift apart.
353pub fn is_ontology_procedure(name: &str) -> bool {
354 builtin_procedure_signature(name)
355 .is_some_and(|signature| signature.name.starts_with("db.ontology."))
356}
357
358/// Whether `name` names a `db.ontology.*` write procedure (`set`, `drop`,
359/// `apply` — ADR-0121 as amended by ADR-0227): registered with the
360/// prefix AND flagged `writes`, both read from the one table.
361pub fn is_ontology_write_procedure(name: &str) -> bool {
362 builtin_procedure_signature(name)
363 .is_some_and(|signature| signature.writes && signature.name.starts_with("db.ontology."))
364}
365
366/// Whether `name` names a store-level ontology op (`db.ontology.set` /
367/// `db.ontology.drop`, ADR-0120 §3) as opposed to the in-overlay `apply`
368/// write or the `get` read. Derived from the one table the way
369/// [`is_ontology_write_procedure`] is: the procedure's signature is flagged
370/// [`ProcSignature::store_level`].
371pub fn is_ontology_store_op(name: &str) -> bool {
372 builtin_procedure_signature(name).is_some_and(|signature| signature.store_level)
373}
374
375/// Whether `CALL name` **could** write — the namespace gate's question: a
376/// store-registered procedure or a built-in flagged `writes` in the
377/// canonical signature registry (ADR-0116 §4). The gate must never admit a
378/// callable to a read view, so registration alone counts.
379///
380/// Its consumer is the facade's namespace write gate (`relate::gate`,
381/// which injects this as the `is_write_procedure` closure the planner's
382/// `is_write` and `plan` take — the planner cannot depend on this registry).
383/// The ADR-0402 effect asks the narrower question, `call_writes_store`.
384pub fn call_is_write(graph: &crate::graph::Graph, name: &str) -> bool {
385 graph.has_procedure(name)
386 || builtin_procedure_signature(name).is_some_and(|signature| signature.writes)
387}
388
389/// Whether `CALL name` writes the store — the ADR-0402 effect question. Only
390/// a writes-flagged built-in does; a store-registered procedure
391/// ([`crate::graph::Procedure`]) is a static row table and cannot mutate the
392/// store, so calling it is no write attempt.
393pub(crate) fn call_writes_store(name: &str) -> bool {
394 builtin_procedure_signature(name).is_some_and(|signature| signature.writes)
395}
396
397/// The replacement when `name` resolves to a deprecated built-in procedure,
398/// `None` otherwise; the procedure-side twin of
399/// [`crate::function_registry::builtin_function_deprecation`] and the one
400/// lookup the query-notification detector reads. The registry's
401/// `deprecated_by` field is the whole deprecation fact — `None` means not
402/// deprecated — so the lookup is a field read, never a bridge between two
403/// flags.
404pub fn builtin_procedure_deprecation(name: &str) -> Option<DeprecatedBy> {
405 builtin_procedure_signature(name)?.deprecated_by
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411
412 /// The lookup reads the one registry: a deprecated entry yields its
413 /// replacement (display text and syntactic form), a current entry and an
414 /// unknown name yield `None`.
415 #[test]
416 fn procedure_deprecation_lookup_reads_the_registry() {
417 assert_eq!(
418 builtin_procedure_deprecation("db.index.vector.queryNodes"),
419 Some(DeprecatedBy::clause("SEARCH"))
420 );
421 assert_eq!(builtin_procedure_deprecation("db.labels"), None);
422 assert_eq!(builtin_procedure_deprecation("no.such.procedure"), None);
423 }
424
425 /// ADR-0463 round 6: the list spelling is exactly `LIST` or `LIST<…>`;
426 /// a bare prefix match would silently accept `LISTS`/`LISTING` as any
427 /// list, re-opening the fail-closed vocabulary.
428 #[test]
429 fn list_type_accepts_only_list_or_list_generic() {
430 let list = Value::List(Vec::new().into());
431 assert!(value_matches_proc_type(&list, "LIST"));
432 assert!(value_matches_proc_type(&list, "LIST<FLOAT>"));
433 assert!(value_matches_proc_type(&list, "list<string>"));
434 assert!(!value_matches_proc_type(&list, "LISTS"));
435 assert!(!value_matches_proc_type(&list, "LISTING"));
436 assert!(!value_matches_proc_type(&Value::Int(1), "LISTS"));
437 }
438
439 #[test]
440 fn every_listed_procedure_has_a_signature() {
441 // The catalog placeholder path is gone: every `SHOW PROCEDURES`
442 // entry renders from this one table.
443 let listed = BUILTIN_PROCEDURE_SIGNATURES
444 .iter()
445 .filter(|s| s.listed)
446 .count();
447 assert!(listed >= 27, "expected the full listed set, got {listed}");
448 }
449
450 #[test]
451 fn vector_query_argument_is_list_of_float() {
452 for name in [
453 "db.index.vector.queryNodes",
454 "db.index.vector.queryRelationships",
455 ] {
456 let sig = builtin_procedure_signature(name).unwrap();
457 assert!(sig.executable);
458 assert_eq!(sig.args[2].name, "query");
459 assert_eq!(sig.args[2].type_str, "LIST<FLOAT>");
460 }
461 }
462
463 /// The description marker every compat-callables signature row and
464 /// front-table entry carries — the shared text the drift guard pins
465 /// both ways: table entries must have matching rows (the forward
466 /// walk), and a row carrying the marker without a table entry is an
467 /// engine-side compat row the front no longer rewrites.
468 const COMPAT_MARKER: &str = "Compatibility (ADR-0699)";
469
470 /// ADR-0699 drift guard, both directions: every compat-callables
471 /// table entry (`relate_front::compat_callables`) carries a matching
472 /// signature row here — executable, listed, no shadowing producer,
473 /// same parameters (names, types, default values), same yield
474 /// columns, same description — and every row carrying the
475 /// compatibility marker belongs to a table entry. Engine
476 /// classification (`writes`, `executable`, `listed`) lives in this
477 /// table alone; membership and bodies in the front table — this test
478 /// is the pin between them.
479 #[test]
480 fn compat_rows_match_the_front_callables_table() {
481 for entry in relate_front::compat_callables::COMPAT_CALLABLES {
482 // Procedure-kind entries pin against this table's rows;
483 // Function-kind entries (independent namespaces, ADR-0382)
484 // pin the inverse — no procedure row may carry their name
485 // until a function-signature home exists for them.
486 if entry.kind == relate_parser::LocalCallableKind::Function {
487 assert!(
488 builtin_procedure_signature(entry.name).is_none(),
489 "compat callable {} is Function-kind but has a procedure signature row; \
490 it needs a function-signature home, not this table's",
491 entry.name
492 );
493 continue;
494 }
495 let signature = builtin_procedure_signature(entry.name)
496 .unwrap_or_else(|| panic!("compat callable {} has no signature row", entry.name));
497 assert!(signature.executable, "{}", entry.name);
498 assert!(signature.listed, "{}", entry.name);
499 assert!(signature.rows.is_none(), "{}", entry.name);
500 // The full per-position parameter shape — name, type, and the
501 // default's VALUE — compared on both sides, so neither table
502 // can drift a parameter (or a default's text) without the
503 // other failing here.
504 let expected: Vec<(&str, &str, Option<&str>)> = entry
505 .params
506 .iter()
507 .map(|param| (param.name, param.ty, param.default))
508 .collect();
509 let declared: Vec<(&str, &str, Option<&str>)> = signature
510 .args
511 .iter()
512 .map(|arg| (arg.name, arg.type_str, arg.default))
513 .collect();
514 assert_eq!(declared, expected, "{}", entry.name);
515 let returns: Vec<&str> = signature.return_columns().collect();
516 assert_eq!(returns, entry.returns, "{}", entry.name);
517 assert_eq!(signature.description, entry.description, "{}", entry.name);
518 }
519 // The converse: an engine row carrying the compatibility marker
520 // whose name the front table no longer rewrites is an orphaned
521 // compat row — executable, listed, advertising a Cypher body
522 // nothing performs.
523 for signature in BUILTIN_PROCEDURE_SIGNATURES {
524 if signature.description.contains(COMPAT_MARKER) {
525 assert!(
526 relate_front::compat_callables::is_compat_callable(signature.name),
527 "{} carries the compatibility marker but is not a compat-callables \
528 table entry",
529 signature.name
530 );
531 }
532 }
533 }
534
535 #[test]
536 fn lookup_is_case_sensitive() {
537 // CIP-230: built-in procedure names are case-sensitive (unlike
538 // function names) -- only the exact declared casing resolves, so
539 // `CALL DB.LABELS()`/`CALL Db.Labels()` are UnknownProcedure errors.
540 assert!(builtin_procedure_signature("db.labels").is_some());
541 assert!(builtin_procedure_signature("DB.LABELS").is_none());
542 assert!(builtin_procedure_signature("Db.Labels").is_none());
543 assert!(builtin_procedure_signature("no.such.procedure").is_none());
544 }
545
546 #[test]
547 fn required_args_stop_at_first_defaulted_parameter() {
548 let await_indexes = builtin_procedure_signature("db.awaitIndexes").unwrap();
549 assert_eq!(await_indexes.args.len(), 1);
550 assert_eq!(await_indexes.required_args(), 0);
551 let labels = builtin_procedure_signature("db.labels").unwrap();
552 assert_eq!(labels.required_args(), 0);
553 let create_label = builtin_procedure_signature("db.createLabel").unwrap();
554 assert_eq!(create_label.required_args(), 1);
555 }
556
557 /// ADR-0121/ADR-0227: the four ontology procedures — no database
558 /// argument, `get` with the `"yaml"` default on `format`.
559 #[test]
560 fn is_ontology_procedure_matches_exactly_the_four() {
561 for name in [
562 "db.ontology.set",
563 "db.ontology.get",
564 "db.ontology.drop",
565 "db.ontology.apply",
566 ] {
567 assert!(is_ontology_procedure(name), "{name}");
568 }
569 for name in [
570 "db.labels",
571 "db.ontology",
572 "DB.ONTOLOGY.SET",
573 "db.ontology.getx",
574 ] {
575 assert!(!is_ontology_procedure(name), "{name}");
576 }
577 }
578
579 /// The write/store-op predicates derive from the one table: `get` is
580 /// not a write, `apply` is a write but not a store op.
581 #[test]
582 fn ontology_write_and_store_op_predicates_split_the_four() {
583 assert!(is_ontology_write_procedure("db.ontology.set"));
584 assert!(is_ontology_write_procedure("db.ontology.drop"));
585 assert!(is_ontology_write_procedure("db.ontology.apply"));
586 assert!(!is_ontology_write_procedure("db.ontology.get"));
587 assert!(!is_ontology_write_procedure("db.labels"));
588
589 assert!(is_ontology_store_op("db.ontology.set"));
590 assert!(is_ontology_store_op("db.ontology.drop"));
591 assert!(!is_ontology_store_op("db.ontology.apply"));
592 assert!(!is_ontology_store_op("db.ontology.get"));
593 assert!(!is_ontology_store_op("db.createLabel"));
594 }
595
596 #[test]
597 fn ontology_procedures_follow_the_revised_contract() {
598 let set = builtin_procedure_signature("db.ontology.set").unwrap();
599 assert!(set.executable && set.listed && set.writes && set.store_level);
600 assert_eq!(set.mode, "SCHEMA");
601 assert_eq!(
602 set.args
603 .iter()
604 .map(|a| (a.name, a.type_str))
605 .collect::<Vec<_>>(),
606 [("ontology", "STRING")]
607 );
608 assert!(set.returns.is_empty());
609
610 let get = builtin_procedure_signature("db.ontology.get").unwrap();
611 assert!(get.executable && get.listed && !get.writes && !get.store_level);
612 assert_eq!(get.mode, "READ");
613 assert_eq!(get.args.len(), 1);
614 assert_eq!(get.args[0].name, "format");
615 assert_eq!(get.args[0].default, Some("\"yaml\""));
616 assert_eq!(get.required_args(), 0);
617 assert_eq!(
618 get.returns
619 .iter()
620 .map(|r| (r.name, r.type_str))
621 .collect::<Vec<_>>(),
622 [("ontology", "STRING")]
623 );
624
625 let drop = builtin_procedure_signature("db.ontology.drop").unwrap();
626 assert!(drop.executable && drop.listed && drop.writes && drop.store_level);
627 assert_eq!(drop.mode, "SCHEMA");
628 assert!(drop.args.is_empty() && drop.returns.is_empty());
629
630 // The one row-producing write of the family (ADR-0667): `apply`
631 // writes and answers its delta row, so it is neither void nor a
632 // store op.
633 let apply = builtin_procedure_signature("db.ontology.apply").unwrap();
634 assert!(apply.executable && apply.listed && apply.writes && !apply.store_level);
635 assert_eq!(apply.mode, "SCHEMA");
636 assert!(apply.args.is_empty());
637 assert_eq!(
638 apply
639 .returns
640 .iter()
641 .map(|r| (r.name, r.type_str))
642 .collect::<Vec<_>>(),
643 [
644 ("ontology", "STRING"),
645 ("constraintsCreated", "INTEGER"),
646 ("constraintsDropped", "INTEGER"),
647 ("skipped", "LIST<STRING>"),
648 ]
649 );
650 }
651
652 #[test]
653 fn writes_flag_marks_exactly_the_graph_or_catalog_mutating_builtins() {
654 // ADR-0116 §4: this set is the single source of truth for the
655 // write-procedure classification the `system_ontologies` read-only
656 // check reads — a name added to or dropped from the table must flip
657 // here, not in a second list.
658 let writes: Vec<&str> = BUILTIN_PROCEDURE_SIGNATURES
659 .iter()
660 .filter(|s| s.writes)
661 .map(|s| s.name)
662 .collect();
663 assert_eq!(
664 writes,
665 [
666 "apoc.create.addLabels",
667 "apoc.merge.relationship",
668 "db.create.setNodeVectorProperty",
669 "db.create.setRelationshipVectorProperty",
670 "db.createLabel",
671 "db.ontology.apply",
672 "db.ontology.drop",
673 "db.ontology.set"
674 ]
675 );
676 }
677
678 /// The corpus's `SHOW PROCEDURES` inventory, row by row (ADR-0497 §6):
679 /// every listed row carries the metadata the catalog renders, and the two
680 /// procedures the corpus has no row for are gone — `SHOW INDEXES` and
681 /// `SHOW CONSTRAINTS` are those surfaces.
682 #[test]
683 fn listed_rows_carry_catalog_metadata_and_the_removed_procedures_are_absent() {
684 for signature in BUILTIN_PROCEDURE_SIGNATURES
685 .iter()
686 .filter(|signature| signature.listed)
687 {
688 assert!(
689 !signature.description.is_empty(),
690 "{} is listed without a description",
691 signature.name
692 );
693 assert!(
694 !signature.mode.is_empty(),
695 "{} is listed without a mode",
696 signature.name
697 );
698 }
699 for removed in ["db.indexes", "db.constraints"] {
700 assert!(
701 builtin_procedure_signature(removed).is_none(),
702 "{removed} must leave the registry"
703 );
704 }
705 }
706
707 /// The policy's `add` rows are all registered with the mode the policy
708 /// states: `db.stats.retrieve` is the one executable addition, the other
709 /// five are listed-only inventory rows.
710 ///
711 /// The server-only families the policy originally added — cluster, routing,
712 /// fleet management, CDC, sessions/connections/locks/pools/JMX/security/
713 /// scheduler, usage statistics, server config, and the vector-property
714 /// setters — are gone: Relate is a single-process embedded engine, so those
715 /// rows advertised capabilities it cannot have (ADR-0557).
716 #[test]
717 fn added_procedures_are_registered_with_the_policys_mode() {
718 let adds = [
719 "db.clearQueryCaches",
720 "db.createProperty",
721 "db.createRelationshipType",
722 "db.listLocks",
723 "db.prepareForReplanning",
724 ];
725 for name in adds {
726 let signature =
727 builtin_procedure_signature(name).unwrap_or_else(|| panic!("{name} missing"));
728 assert!(signature.listed, "{name} must be listed");
729 assert!(!signature.executable, "{name} is catalog-only");
730 assert!(!signature.description.is_empty(), "{name}");
731 }
732 let retrieve = builtin_procedure_signature("db.stats.retrieve").expect("registered");
733 assert!(retrieve.listed && retrieve.executable);
734 assert_eq!(retrieve.mode, "READ");
735 assert_eq!(
736 retrieve
737 .returns
738 .iter()
739 .map(|ret| (ret.name, ret.type_str))
740 .collect::<Vec<_>>(),
741 [("section", "STRING"), ("data", "MAP")]
742 );
743 }
744
745 /// ADR-0143: the Browser/Desktop-compat `dbms.*` procedures stay callable
746 /// with the exact pinned return columns; ADR-0497 §6 makes every one of
747 /// them but `dbms.clientConfig` and `dbms.licenseAgreementDetails` a
748 /// listed `SHOW PROCEDURES` row, because the corpus inventories them.
749 #[test]
750 fn adr0143_procedures_keep_their_pinned_columns_and_corpus_listing() {
751 let show_current_user =
752 builtin_procedure_signature("dbms.showCurrentUser").expect("registered");
753 assert!(show_current_user.executable);
754 assert!(show_current_user.listed);
755 assert!(show_current_user.args.is_empty());
756 assert_eq!(
757 show_current_user
758 .returns
759 .iter()
760 .map(|r| (r.name, r.type_str))
761 .collect::<Vec<_>>(),
762 [
763 ("username", "STRING"),
764 ("roles", "LIST<STRING>"),
765 ("flags", "LIST<STRING>")
766 ]
767 );
768
769 // dbms.clientConfig and dbms.listConfig deliberately share one
770 // return-column list: same names, same types, same order, no args.
771 let client_config = builtin_procedure_signature("dbms.clientConfig").expect("registered");
772 let list_config = builtin_procedure_signature("dbms.listConfig").expect("registered");
773 assert!(client_config.executable && !client_config.listed);
774 assert!(list_config.executable && list_config.listed);
775 assert!(client_config.args.is_empty() && list_config.args.is_empty());
776 assert!(std::ptr::eq(client_config.returns, list_config.returns));
777 assert_eq!(
778 client_config
779 .returns
780 .iter()
781 .map(|r| (r.name, r.type_str))
782 .collect::<Vec<_>>(),
783 [
784 ("name", "STRING"),
785 ("description", "STRING"),
786 ("value", "STRING"),
787 ("dynamic", "BOOLEAN"),
788 ("defaultValue", "STRING"),
789 ("startupValue", "STRING"),
790 ("explicitlySet", "BOOLEAN"),
791 ("validValues", "STRING")
792 ]
793 );
794
795 let license =
796 builtin_procedure_signature("dbms.licenseAgreementDetails").expect("registered");
797 assert!(license.executable);
798 assert!(!license.listed);
799 assert!(license.args.is_empty());
800 assert_eq!(
801 license
802 .returns
803 .iter()
804 .map(|r| (r.name, r.type_str))
805 .collect::<Vec<_>>(),
806 [
807 ("status", "STRING"),
808 ("daysLeftOnTrial", "INTEGER"),
809 ("totalTrialDays", "INTEGER")
810 ]
811 );
812 }
813}