use relate_core::Value;
use crate::catalog_meta::{DeprecatedBy, ProcArgMeta};
#[derive(Clone, Copy, Debug)]
pub(crate) enum RowProducer {
TxGetMetaData,
DbmsComponents,
DbPing,
DbLabels,
DbRelationshipTypes,
DbPropertyKeys,
DbInfo,
DbmsInfo,
DbmsShowCurrentUser,
DbmsConfig,
DbmsLicenseAgreementDetails,
DbmsListCapabilities,
FulltextAnalyzers,
DbStatsRetrieve,
SchemaNodeTypeProperties,
SchemaRelTypeProperties,
SchemaVisualization,
}
pub struct ProcSignature {
pub name: &'static str,
pub description: &'static str,
pub mode: &'static str,
pub works_on_system: bool,
pub admin: bool,
pub(crate) args: &'static [ProcArgMeta],
pub(crate) returns: &'static [ProcArgMeta],
pub deprecated_by: Option<DeprecatedBy>,
pub executable: bool,
pub listed: bool,
pub(crate) rows: Option<RowProducer>,
pub writes: bool,
pub store_level: bool,
}
impl ProcSignature {
pub(crate) const fn read(name: &'static str) -> Self {
Self {
name,
description: "",
mode: "READ",
works_on_system: false,
admin: false,
args: &[],
returns: &[],
deprecated_by: None,
executable: true,
listed: true,
writes: false,
store_level: false,
rows: None,
}
}
pub(crate) const fn dbms(name: &'static str) -> Self {
let mut sig = Self::read(name);
sig.mode = "DBMS";
sig
}
pub(crate) const fn write(name: &'static str) -> Self {
let mut sig = Self::read(name);
sig.mode = "WRITE";
sig
}
pub(crate) const fn schema(name: &'static str) -> Self {
let mut sig = Self::read(name);
sig.mode = "SCHEMA";
sig
}
pub(crate) const fn rows(mut self, rows: RowProducer) -> Self {
self.rows = Some(rows);
self
}
pub(crate) const fn works_on_system(mut self) -> Self {
self.works_on_system = true;
self
}
pub(crate) const fn described(mut self, description: &'static str) -> Self {
self.description = description;
self
}
pub(crate) const fn admin(mut self) -> Self {
self.admin = true;
self
}
pub(crate) const fn writes(mut self) -> Self {
self.writes = true;
self
}
pub(crate) const fn store_level(mut self) -> Self {
self.store_level = true;
self
}
pub(crate) const fn args(mut self, args: &'static [ProcArgMeta]) -> Self {
self.args = args;
self
}
pub(crate) const fn returns(mut self, returns: &'static [ProcArgMeta]) -> Self {
self.returns = returns;
self
}
pub(crate) const fn deprecated_by(mut self, by: DeprecatedBy) -> Self {
self.deprecated_by = Some(by);
self
}
pub(crate) const fn executable(mut self, executable: bool) -> Self {
self.executable = executable;
self
}
pub(crate) const fn listed(mut self, listed: bool) -> Self {
self.listed = listed;
self
}
}
impl ProcSignature {
pub fn required_args(&self) -> usize {
self.args.iter().take_while(|a| a.default.is_none()).count()
}
pub fn parameters(&self) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
self.args.iter().map(|arg| (arg.name, arg.type_str))
}
pub fn return_columns(&self) -> impl Iterator<Item = &'static str> + '_ {
self.returns.iter().map(|ret| ret.name)
}
pub(crate) fn is_void(&self) -> bool {
self.returns.is_empty()
}
}
mod signatures;
pub use signatures::BUILTIN_PROCEDURE_SIGNATURES;
pub fn builtin_procedure_signature(name: &str) -> Option<&'static ProcSignature> {
BUILTIN_PROCEDURE_SIGNATURES
.iter()
.find(|sig| sig.name == name)
}
pub fn is_void_procedure(registered: Option<&crate::graph::Procedure>, name: &str) -> bool {
if let Some(procedure) = registered {
return procedure.yield_names.is_empty();
}
builtin_procedure_signature(name).is_some_and(ProcSignature::is_void)
}
pub fn value_matches_proc_type(v: &Value, ty: &str) -> bool {
matches_normalized_type(v, &normalize_proc_type(ty))
}
pub(crate) fn normalize_proc_type(ty: &str) -> String {
ty.trim().trim_end_matches('?').trim().to_ascii_uppercase()
}
pub(crate) fn matches_normalized_type(v: &Value, ty: &str) -> bool {
if v.is_null() || ty.is_empty() || ty == "ANY" {
return true;
}
if ty.contains('|') {
return ty
.split('|')
.any(|alternative| matches_normalized_type(v, alternative.trim()));
}
if ty == "LIST" || ty.starts_with("LIST<") {
return matches!(v, Value::List(_));
}
match ty {
"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 fn is_ontology_procedure(name: &str) -> bool {
builtin_procedure_signature(name)
.is_some_and(|signature| signature.name.starts_with("db.ontology."))
}
pub fn is_ontology_write_procedure(name: &str) -> bool {
builtin_procedure_signature(name)
.is_some_and(|signature| signature.writes && signature.name.starts_with("db.ontology."))
}
pub fn is_ontology_store_op(name: &str) -> bool {
builtin_procedure_signature(name).is_some_and(|signature| signature.store_level)
}
pub fn call_is_write(graph: &crate::graph::Graph, name: &str) -> bool {
graph.has_procedure(name)
|| builtin_procedure_signature(name).is_some_and(|signature| signature.writes)
}
pub(crate) fn call_writes_store(name: &str) -> bool {
builtin_procedure_signature(name).is_some_and(|signature| signature.writes)
}
pub fn builtin_procedure_deprecation(name: &str) -> Option<DeprecatedBy> {
builtin_procedure_signature(name)?.deprecated_by
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn procedure_deprecation_lookup_reads_the_registry() {
assert_eq!(
builtin_procedure_deprecation("db.index.vector.queryNodes"),
Some(DeprecatedBy::clause("SEARCH"))
);
assert_eq!(builtin_procedure_deprecation("db.labels"), None);
assert_eq!(builtin_procedure_deprecation("no.such.procedure"), None);
}
#[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"));
}
#[test]
fn every_listed_procedure_has_a_signature() {
let listed = BUILTIN_PROCEDURE_SIGNATURES
.iter()
.filter(|s| s.listed)
.count();
assert!(listed >= 27, "expected the full listed set, got {listed}");
}
#[test]
fn vector_query_argument_is_list_of_float() {
for name in [
"db.index.vector.queryNodes",
"db.index.vector.queryRelationships",
] {
let sig = builtin_procedure_signature(name).unwrap();
assert!(sig.executable);
assert_eq!(sig.args[2].name, "query");
assert_eq!(sig.args[2].type_str, "LIST<FLOAT>");
}
}
const COMPAT_MARKER: &str = "Compatibility (ADR-0699)";
#[test]
fn compat_rows_match_the_front_callables_table() {
for entry in relate_front::compat_callables::COMPAT_CALLABLES {
if entry.kind == relate_parser::LocalCallableKind::Function {
assert!(
builtin_procedure_signature(entry.name).is_none(),
"compat callable {} is Function-kind but has a procedure signature row; \
it needs a function-signature home, not this table's",
entry.name
);
continue;
}
let signature = builtin_procedure_signature(entry.name)
.unwrap_or_else(|| panic!("compat callable {} has no signature row", entry.name));
assert!(signature.executable, "{}", entry.name);
assert!(signature.listed, "{}", entry.name);
assert!(signature.rows.is_none(), "{}", entry.name);
let expected: Vec<(&str, &str, Option<&str>)> = entry
.params
.iter()
.map(|param| (param.name, param.ty, param.default))
.collect();
let declared: Vec<(&str, &str, Option<&str>)> = signature
.args
.iter()
.map(|arg| (arg.name, arg.type_str, arg.default))
.collect();
assert_eq!(declared, expected, "{}", entry.name);
let returns: Vec<&str> = signature.return_columns().collect();
assert_eq!(returns, entry.returns, "{}", entry.name);
assert_eq!(signature.description, entry.description, "{}", entry.name);
}
for signature in BUILTIN_PROCEDURE_SIGNATURES {
if signature.description.contains(COMPAT_MARKER) {
assert!(
relate_front::compat_callables::is_compat_callable(signature.name),
"{} carries the compatibility marker but is not a compat-callables \
table entry",
signature.name
);
}
}
}
#[test]
fn lookup_is_case_sensitive() {
assert!(builtin_procedure_signature("db.labels").is_some());
assert!(builtin_procedure_signature("DB.LABELS").is_none());
assert!(builtin_procedure_signature("Db.Labels").is_none());
assert!(builtin_procedure_signature("no.such.procedure").is_none());
}
#[test]
fn required_args_stop_at_first_defaulted_parameter() {
let await_indexes = builtin_procedure_signature("db.awaitIndexes").unwrap();
assert_eq!(await_indexes.args.len(), 1);
assert_eq!(await_indexes.required_args(), 0);
let labels = builtin_procedure_signature("db.labels").unwrap();
assert_eq!(labels.required_args(), 0);
let create_label = builtin_procedure_signature("db.createLabel").unwrap();
assert_eq!(create_label.required_args(), 1);
}
#[test]
fn is_ontology_procedure_matches_exactly_the_four() {
for name in [
"db.ontology.set",
"db.ontology.get",
"db.ontology.drop",
"db.ontology.apply",
] {
assert!(is_ontology_procedure(name), "{name}");
}
for name in [
"db.labels",
"db.ontology",
"DB.ONTOLOGY.SET",
"db.ontology.getx",
] {
assert!(!is_ontology_procedure(name), "{name}");
}
}
#[test]
fn ontology_write_and_store_op_predicates_split_the_four() {
assert!(is_ontology_write_procedure("db.ontology.set"));
assert!(is_ontology_write_procedure("db.ontology.drop"));
assert!(is_ontology_write_procedure("db.ontology.apply"));
assert!(!is_ontology_write_procedure("db.ontology.get"));
assert!(!is_ontology_write_procedure("db.labels"));
assert!(is_ontology_store_op("db.ontology.set"));
assert!(is_ontology_store_op("db.ontology.drop"));
assert!(!is_ontology_store_op("db.ontology.apply"));
assert!(!is_ontology_store_op("db.ontology.get"));
assert!(!is_ontology_store_op("db.createLabel"));
}
#[test]
fn ontology_procedures_follow_the_revised_contract() {
let set = builtin_procedure_signature("db.ontology.set").unwrap();
assert!(set.executable && set.listed && set.writes && set.store_level);
assert_eq!(set.mode, "SCHEMA");
assert_eq!(
set.args
.iter()
.map(|a| (a.name, a.type_str))
.collect::<Vec<_>>(),
[("ontology", "STRING")]
);
assert!(set.returns.is_empty());
let get = builtin_procedure_signature("db.ontology.get").unwrap();
assert!(get.executable && get.listed && !get.writes && !get.store_level);
assert_eq!(get.mode, "READ");
assert_eq!(get.args.len(), 1);
assert_eq!(get.args[0].name, "format");
assert_eq!(get.args[0].default, Some("\"yaml\""));
assert_eq!(get.required_args(), 0);
assert_eq!(
get.returns
.iter()
.map(|r| (r.name, r.type_str))
.collect::<Vec<_>>(),
[("ontology", "STRING")]
);
let drop = builtin_procedure_signature("db.ontology.drop").unwrap();
assert!(drop.executable && drop.listed && drop.writes && drop.store_level);
assert_eq!(drop.mode, "SCHEMA");
assert!(drop.args.is_empty() && drop.returns.is_empty());
let apply = builtin_procedure_signature("db.ontology.apply").unwrap();
assert!(apply.executable && apply.listed && apply.writes && !apply.store_level);
assert_eq!(apply.mode, "SCHEMA");
assert!(apply.args.is_empty());
assert_eq!(
apply
.returns
.iter()
.map(|r| (r.name, r.type_str))
.collect::<Vec<_>>(),
[
("ontology", "STRING"),
("constraintsCreated", "INTEGER"),
("constraintsDropped", "INTEGER"),
("skipped", "LIST<STRING>"),
]
);
}
#[test]
fn writes_flag_marks_exactly_the_graph_or_catalog_mutating_builtins() {
let writes: Vec<&str> = BUILTIN_PROCEDURE_SIGNATURES
.iter()
.filter(|s| s.writes)
.map(|s| s.name)
.collect();
assert_eq!(
writes,
[
"apoc.create.addLabels",
"apoc.merge.relationship",
"db.create.setNodeVectorProperty",
"db.create.setRelationshipVectorProperty",
"db.createLabel",
"db.ontology.apply",
"db.ontology.drop",
"db.ontology.set"
]
);
}
#[test]
fn listed_rows_carry_catalog_metadata_and_the_removed_procedures_are_absent() {
for signature in BUILTIN_PROCEDURE_SIGNATURES
.iter()
.filter(|signature| signature.listed)
{
assert!(
!signature.description.is_empty(),
"{} is listed without a description",
signature.name
);
assert!(
!signature.mode.is_empty(),
"{} is listed without a mode",
signature.name
);
}
for removed in ["db.indexes", "db.constraints"] {
assert!(
builtin_procedure_signature(removed).is_none(),
"{removed} must leave the registry"
);
}
}
#[test]
fn added_procedures_are_registered_with_the_policys_mode() {
let adds = [
"db.clearQueryCaches",
"db.createProperty",
"db.createRelationshipType",
"db.listLocks",
"db.prepareForReplanning",
];
for name in adds {
let signature =
builtin_procedure_signature(name).unwrap_or_else(|| panic!("{name} missing"));
assert!(signature.listed, "{name} must be listed");
assert!(!signature.executable, "{name} is catalog-only");
assert!(!signature.description.is_empty(), "{name}");
}
let retrieve = builtin_procedure_signature("db.stats.retrieve").expect("registered");
assert!(retrieve.listed && retrieve.executable);
assert_eq!(retrieve.mode, "READ");
assert_eq!(
retrieve
.returns
.iter()
.map(|ret| (ret.name, ret.type_str))
.collect::<Vec<_>>(),
[("section", "STRING"), ("data", "MAP")]
);
}
#[test]
fn adr0143_procedures_keep_their_pinned_columns_and_corpus_listing() {
let show_current_user =
builtin_procedure_signature("dbms.showCurrentUser").expect("registered");
assert!(show_current_user.executable);
assert!(show_current_user.listed);
assert!(show_current_user.args.is_empty());
assert_eq!(
show_current_user
.returns
.iter()
.map(|r| (r.name, r.type_str))
.collect::<Vec<_>>(),
[
("username", "STRING"),
("roles", "LIST<STRING>"),
("flags", "LIST<STRING>")
]
);
let client_config = builtin_procedure_signature("dbms.clientConfig").expect("registered");
let list_config = builtin_procedure_signature("dbms.listConfig").expect("registered");
assert!(client_config.executable && !client_config.listed);
assert!(list_config.executable && list_config.listed);
assert!(client_config.args.is_empty() && list_config.args.is_empty());
assert!(std::ptr::eq(client_config.returns, list_config.returns));
assert_eq!(
client_config
.returns
.iter()
.map(|r| (r.name, r.type_str))
.collect::<Vec<_>>(),
[
("name", "STRING"),
("description", "STRING"),
("value", "STRING"),
("dynamic", "BOOLEAN"),
("defaultValue", "STRING"),
("startupValue", "STRING"),
("explicitlySet", "BOOLEAN"),
("validValues", "STRING")
]
);
let license =
builtin_procedure_signature("dbms.licenseAgreementDetails").expect("registered");
assert!(license.executable);
assert!(!license.listed);
assert!(license.args.is_empty());
assert_eq!(
license
.returns
.iter()
.map(|r| (r.name, r.type_str))
.collect::<Vec<_>>(),
[
("status", "STRING"),
("daysLeftOnTrial", "INTEGER"),
("totalTrialDays", "INTEGER")
]
);
}
}